How to scroll HTML page to given anchor?

后端 未结 17 1797
醉梦人生
醉梦人生 2020-11-22 08:55

I’d like to make the browser to scroll the page to a given anchor, just by using JavaScript.

I have specified a name or id attribute in my

17条回答
  •  醉酒成梦
    2020-11-22 09:07

    I know this is question is really old, but I found an easy and simple jQuery solution in css-tricks. That's the one I'm using now.

    $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 1000);
            return false;
          }
        }
      });
    });
    

提交回复
热议问题