如何通过javascript将浏览器滚动到所需的元素?

时间:2012-08-09 09:32:39

标签: javascript html browser

问题很简单。

如何通过javascript将浏览器滚动到所需的元素或所需的位置?

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:9)

要素:

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

Has cross browser support可能是最简单的方法....

或特定职位:

window.scroll(x,y);

Docs for window.scroll() here

答案 1 :(得分:1)

//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));