How can I make the page scroll to an element?
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
精彩评论