How to scroll HTML page to given anchor?

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

    You can use jQuerys .animate(), .offset() and scrollTop. Like

    $(document.body).animate({
        'scrollTop':   $('#anchorName2').offset().top
    }, 2000);
    

    example link: http://jsbin.com/unasi3/edit

    If you don't want to animate use .scrollTop() like

    $(document.body).scrollTop($('#anchorName2').offset().top);
    

    or javascripts native location.hash like

    location.hash = '#' + anchorid;
    

提交回复
热议问题