Javascript ScrollTop 在 IE 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6736849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ScrollTop not working in IE
提问by Odinulf
Anyone have any ideas why scrollTop isn't working in IE?
任何人都知道为什么 scrollTop 在 IE 中不起作用?
It works in Chrome fine, and I don't know about firefox. (The idea of this script is to have an autoscrolling page that resets once it hits the bottom of the page)
它在 Chrome 中运行良好,我不知道 firefox。(这个脚本的想法是有一个自动滚动页面,一旦它到达页面底部就会重置)
function getheight() {
var myWidth = 0,
myHeight = 0;
if (typeof (window.innerWidth) == 'number') {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
var scrolledtonum = window.pageYOffset + myHeight + 2;
var heightofbody = document.body.offsetHeight;
if (scrolledtonum >= heightofbody) {
document.body.scrollTop(0, 0);
}
}
window.onscroll = getheight;
function func() {
window.document.body.scrollTop++;
}
window.document.onmouseover = function () {
clearInterval(interval);
};
window.document.onmouseout = function () {
interval = setInterval(func, 20);
};
var interval = setInterval(func, 20);
回答by Trevor
Try:
尝试:
document.documentElement.scrollTop = x // where x is some integer
回答by Chetan
Try this
尝试这个
window.scroll(0,0) //x-axis, y-axis
window.scroll(0,0) //x轴,y轴
回答by nwellcome
The reason things like this don't work on one browser or another is usually due to something like:
这样的事情在一个或另一个浏览器上不起作用的原因通常是由于:
window.document.body.scrollTop++;
You can't just do that because some browsers have that value as a string, e.g. "5px" and some have it as a number.
您不能这样做,因为有些浏览器将该值作为字符串,例如“5px”,而有些浏览器将其作为数字。
回答by vanrado
Solution for EDGE needs to set scrollTop on scrollingElementdocument property:
EDGE 需要在 scrollingElement文档属性上设置scrollTop 的解决方案:
document.scrollingElement.scrollTop= x; // x is integer value
But you have to ensure, that CSS on HTML element has set overflow to default value (visible):
但是您必须确保 HTML 元素上的 CSS 已将溢出设置为默认值(可见):
html {
overflow: visible;
}
回答by Alvaro
If you need it to work in IE and Edge:
如果您需要它在 IE 和 Edge 中工作:
document.body.scrollTop = x