修复平滑滚动问题

Fixing Smooth Scroll Issue

我正在使用的简化版本:http://jimmehrabbitdesigns.com/scroll.html

我可以使用滚动功能,但是,它不会从一个部分过渡到另一个部分。

示例:如果您单击数字 3,它将滚动到第三部分。从那里开始,这就是发生的事情。
- 单击数字 2 将带您返回第一部分。
- 单击数字 4 会将您带到第二部分。
- 再次单击数字 3 也会将您带回第一部分。

这对所有部分都是一样的。


jQuery 使用代码:

$('a[href*="#"]:not([href="#"])').click(function () {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            $('#right').animate({ scrollTop: target.offset().top }, 1000);
            return false;
        }
    }
});

我稍微修改了你的代码。它更简单,可以帮助您了解正在发生的事情。希望对你有帮助:

/*
1. I've changed the position fixed to position absolute on the #right element, the scroll won't work with position: fixed set
2. Added the on click event on the anchor tag this way I'm getting the href of the current clicked anchor by using $(this) and attr() method 
3. Added the e.preventdefault() to prevent the default action of the anchor element 
4. Doing the smooth scroll using the href got at 2 as id selector
*/

jQuery 代码如下所示:

$('#left a').on('click', function(e) {
  e.preventDefault();
  var id = $(this).attr('href');
  $('html, body').animate({
    scrollTop: $(id).offset().top
  }, 1000);
});

您可以点击下面的按钮查看完整的工作片段:

$('#left a').on('click', function(e) { 
    e.preventDefault(); 
    var id = $(this).attr('href');
     $('html, body').animate({
        scrollTop: $(id).offset().top
    }, 1000);
});
html {
  width: 100%;
  height: 100%;
}
body {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
#left {
  width: 100%;
  height: 100%;
  background-color: #FFFFFF;
  position: fixed;
  top: 0;
  left: 0;
}
#right {
  width: 50%;
  height: 100%;
  background-color: #0000FF;
  position: absolute;
  top: 0;
  right: 0;
  z-index: 1;
}
#one {
  height: 100%;
  background-color: #FF0000;
}
#two {
  height: 100%;
  background-color: #00FF00;
}
#three {
  height: 100%;
  background-color: #FFFF00;
}
#four {
  height: 100%;
  background-color: #00FFFF;
}
#five {
  height: 100%;
  background-color: #FF00FF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
  <div id="left">
    <a href="#one">NUMBER 1</a>
    <br>
    <a href="#two">NUMBER 2</a>
    <br>
    <a href="#three">NUMBER 3</a>
    <br>
    <a href="#four">NUMBER 4</a>
    <br>
    <a href="#five">NUMBER 5</a>
  </div>
  <div id="right">
    <div id="one" width="100%" height="100%">ONE</div>
    <div id="two" width="100%" height="100%">TWO</div>
    <div id="three" width="100%" height="100%">THREE</div>
    <div id="four" width="100%" height="100%">FOUR</div>
    <div id="five" width="100%" height="100%">FIVE</div>
  </div>
</div>

你也可以查看这个JSFIDDLE