简体   繁体   中英

Anchor scrolling jQuery

I found this example . The code is quite old though, but it seems to do what I'm looking for:

jQuery(document).ready(function($) {
  $(".scroll").click(function(event){
    event.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
  });
});

And secondly, is it possible to make all anchors between a div called "navigation" to have this functionality, instead of adding a "scroll" class to every anchor?

Example:

<div id="section1">Scroll to me :P</div>

For your second question, sounds like you want to attach the click handler to all children of a chosen element. Do it using .on :

$("#navigation").on("click", "a", function(event) {
    event.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});

Where "#navigation" is the selector of the parent element you want, and "a" is a selector for the children.

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