How to scroll HTML page to given anchor?

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

    Smoothly scroll to the proper position (2019)

    Get correct y coordinate and use window.scrollTo({top: y, behavior: 'smooth'})

    const id = 'anchorName2';
    const yourElement = document.getElementById(id);
    const y = yourElement.getBoundingClientRect().top + window.pageYOffset;
    
    window.scrollTo({top: y, behavior: 'smooth'});
    

    With offset

    scrollIntoView is a good option too but it may not works perfectly in some cases. For example when you need additional offset. With scrollTo you just need to add that offset like this:

    const yOffset = -10; 
    
    window.scrollTo({top: y + yOffset, behavior: 'smooth'});
    

提交回复
热议问题