简体   繁体   中英

Jquery Smooth Scroll Using Offset.top

I'm attempting to create a smooth scrolling effect from a topNav to various sections on a webpage. 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.

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. 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?

If so, you made a little mistake in your HTML. Href attribute reference an ID, not a name attribute !

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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