开发者

How can I make the page scroll to an element?

开发者 https://www.devze.com 2023-04-13 05:16 出处:网络
I would like to scroll开发者_开发知识库 to an element (make it visible for user) even if the element is on the bottom of the page.

I would like to scroll开发者_开发知识库 to an element (make it visible for user) even if the element is on the bottom of the page.

I tried

document.getElementById('idOfLink').focus();

but if the element is on the bottom of a very long page its not visible to the user.


There are two possible methods, each suitable in different scenarios:

You can use scrollIntoView(), which will scroll the element into view but will not add save the "state" for when the user presses the back button:

document.getElementById('idOfLink').scrollIntoView();

If you want back button support, you will need to modify window.location.hash:

window.location.hash = 'idOfLink';


You can use the hash tag as it was originally intended:

window.location.hash = "idOfLink"

Example

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号