简体   繁体   English

使用Offset.top的jQuery平滑滚动

[英]Jquery Smooth Scroll Using Offset.top

I'm attempting to create a smooth scrolling effect from a topNav to various sections on a webpage. 我正在尝试从topNav到网页的各个部分创建平滑的滚动效果。 In the code below, I've recreated the issue I'm having, which is simply I can't seem to have the scroll process animated. 在下面的代码中,我重新创建了我遇到的问题,这简直使我似乎无法使滚动过程变得生动起来。 My links jump to the proper sections, and I've console.logged along the way to make sure the proper elements are being grabbed at the time of the 'click' but it is still not working. 我的链接跳至相应的部分,并且在进行console.logged已进行了console.logged ,以确保在'click'时捕获了正确的元素,但仍无法正常工作。

Can anyone assist? 有人可以协助吗? Initially I thought it might have to do with the fact that instead of giving the navlinks individual IDs, I grouped them with a class name. 最初,我认为这可能与以下事实有关:我没有给navlinks单独的ID,而是将它们与类名组合在一起。 Could that be part of my problem? 那可能是我的问题吗?

 $(document).ready(function() { $('.slide').click(function() { var link = $(this).attr('href'); $('html,body').animate({ scrollTop: $(link).offset().top}, 1000); return false; }); }); 
 * { padding: 0; margin: 0; } nav { width: 100%; height: 120px; } div { width: 100%; height: 500px; } 
 <nav> <a href="#first" class="slide">Section 1</a> <a href="#second" class="slide">Section 2</a> <a href="#third" class="slide">Section 3</a> <a href="#fourth" class="slide">Section 4</a> </nav> <div> <a name="first">Section 1</a> </div> <div> <a name="second">Section 2</a> </div> <div> <a name="third">Section 3</a> </div> <div> <a name="fourth">Section 4</a> </div> 

First, did you load JQuery in your project? 首先,您是否在项目中加载了JQuery?

If so, you made a little mistake in your HTML. 如果是这样,则您在HTML中犯了一个小错误。 Href attribute reference an ID, not a name attribute ! Href属性引用一个ID,而不是name属性!

My solution : 我的解决方案:

 $(document).ready(function() { $('.slide').click(function() { var link = $(this).attr('href'); $('html, body').animate({ scrollTop: $(link).offset().top}, 1000); return false; }); }); 
 * { padding: 0; margin: 0; } nav { width: 100%; height: 120px; } div { width: 100%; height: 500px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav> <a href="#first" class="slide">Section 1</a> <a href="#second" class="slide">Section 2</a> <a href="#third" class="slide">Section 3</a> <a href="#fourth" class="slide">Section 4</a> </nav> <div id="first"> <a>Section 1</a> </div> <div id="second"> <a>Section 2</a> </div> <div id="third"> <a>Section 3</a> </div> <div id="four"> <a>Section 4</a> </div> 

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

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