How to scroll browser to desired element by javascript?

[亡魂溺海] 提交于 2020-01-02 18:07:49

问题


The question is simple.

How to scroll browser to desired element or desired position by javascript?

Thanks a lot for the help!


回答1:


To an element :

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

Has cross browser support and probably the easiest way to do it ....

or to a specific position :

window.scroll(x,y);

Docs for window.scroll() here




回答2:


//Finds y value of given object
function findPos(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    return [curtop];
    }
}
//Get object
var SupportDiv = document.getElementById('customer_info');

//Scroll to location of SupportDiv on load
window.scroll(0,findPos(SupportDiv));


来源:https://stackoverflow.com/questions/11880443/how-to-scroll-browser-to-desired-element-by-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!