How to scroll HTML page to given anchor?

后端 未结 17 1966
醉梦人生
醉梦人生 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:00

    The solution from CSS-Tricks no longer works in jQuery 2.2.0. It will throw a selector error:

    JavaScript runtime error: Syntax error, unrecognized expression: a[href*=#]:not([href=#])

    I fixed it by changing the selector. The full snippet is this:

    $(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;
        }
      }
     });
    });
    

提交回复
热议问题