1

动画 scrollTop 属性是否渲染不准确。请检查我在 jsbin http://jsbin.com/ewulum/2/edit中制作的这段代码

我想做的是,当点击链接时,它会自动向下滚动到相应的部分。但是我无法弄清楚为什么不能正确向下滚动到相应部分的代码有什么问题。单击前两个链接似乎工作正常。

提前致谢。

4

2 回答 2

1

实际上它正在工作并且动画 jQuery scrollTop 工作正常。只需添加height:2000pxbodyCSS。当您单击第 3、4 或 5 个链接时,它会向下滚动,因为第 5 部分下没有空间,所以滚动停止。在其下方添加一些空间或在容器上添加高度应该可以解决您的问题。

于 2013-05-29T06:31:09.220 回答
0

在我看来一切都很好。滚动到特定元素的最相关代码是:

$('html, body').animate({ scrollTop: $('#box').offset().top }, 2000);

您可以根据需要添加额外的像素以完美定位它。

$('html, body').animate({ scrollTop: $('#box').offset().top + 10 }, 2000);

我进入了您的http://jsbin.com/ewulum/2/edit并进行了一些更改:

.wrapper {
  width: 90%;
  margin: 0 auto;
  background:#ececec;
  overflow: auto;
  height: 250px;
}

JS文件

//event delegation
$("#nav-wrapper").on("click", "a", function(e){

  var cur_el_href = $(this).attr("href"),
      cur_el_top =$(cur_el_href).offset().top;

  e.preventDefault();

  console.log("The current elem's href value is " + cur_el_href);
  console.log("The target section's offset top is " + cur_el_top);

 $(".wrapper").animate({
     scrollTop:cur_el_top
   },
   800, function(){
     //this callback is for demonstration only so as not to back to top when testing other links
         $(this).animate({scrollTop:0}, 1000);
   });

});
于 2013-05-29T06:58:26.710 回答