简体   繁体   English

jQuery动画scrollTop

[英]jQuery animate scrollTop

I have quite a few section tags in a div with an overflow set to hidden . 我在div中有很多section标签,溢出设置为hidden The code is along the lines of this: 代码是这样的:


<div id="viewport">
   <section>
      content
   </section>
   <section>
      content
   </section>
</div>

I have it set up like this because I want to be able to scroll through the sections contained within the div when the corresponding link is pressed in the menu. 我把它设置为这样,因为我希望能够在菜单中按下相应的链接时滚动div包含的sections I have this function: 我有这个功能:


$('#mn a').click(function(){
   var aHref = $(this).attr("href");
   var sectionHeight = $('section'+aHref+'').height();
   $('#viewport').height(sectionHeight);
});

Which I use to resize the #viewport div because the sections are different sizes. 我用它来调整#viewport div的大小,因为这些sections的大小不同。 When I try to put this scroll part into that function: 当我尝试将此滚动部分放入该函数时:


$('body,html').animate({scrollTop: $(aHref).offset().top}, 800);

it makes the entire page scroll. 它使整个页面滚动。 When I try to replace $('body,html') with $('section, #viewport') it scrolls inside the div, but it doesn't do so properly. 当我尝试用$('section, #viewport')替换$('body,html')$('section, #viewport')它会在div中滚动,但它没有正确地执行。

I have a live example of this here . 在这里有一个实例。 I assume it has something to do with either the .offset() or what I'm passing into the .animate() , but I've tried quite a few different things but to no avail. 我认为它与.offset()或我传入.animate() ,但我尝试了很多不同的东西,但无济于事。 Can someone please point me in the right direction or tell me what I've done wrong? 有人可以指出我正确的方向或告诉我我做错了什么?

The problem is how position() works, it returns top/height related to scrollTop . 问题是position()如何工作,它返回与scrollTop相关的top / height。

So if you request at click $('section'+aHref+'').position().top the position returned is modified from scrollTop value. 因此,如果您请求点击$('section'+aHref+'').position().top返回的位置是从scrollTop值修改的。

You can get all height position at ready event. 您可以在准备好的活动中获得所有高度位置。 (so scrollTop is 0 ) (所以scrollTop0

Or you can sanitize position values with: 或者您可以使用以下方法清理位置值:

$("section#skills").position().top + $("#viewport").scrollTop()

First of all you should prevent the default behavior of the anchor in order to scroll the page to the top of the page. 首先,您应该阻止锚点的默认行为,以便将页面滚动到页面顶部。 You can do this by calling preventDefault() method on the event object inside click event handler. 您可以通过在click事件处理程序内的事件对象上调用preventDefault()方法来完成此操作。 Try this 试试这个

$('#mn a').click(function(e){
   e.preventDefault();

   var aHref = $(this).attr("href");
   var top = $('section'+aHref+'').position().top;
   $('#viewport').animate({scrollTop: top}, 800);
});

如果你想要一个简单的jquery插件来执行此操作,那么你可以尝试( AnimateScroll ),它目前也支持超过30种缓动样式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM