在IE中,ScrollTop不起作用

11

有人知道为什么在IE中scrollTop无法正常工作吗?

在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);
5个回答

23

尝试:

document.documentElement.scrollTop = x // where x is some integer

6

尝试这个

window.scroll(0,0) // x轴,y轴


如何使其动画化或减慢速度。 - panky sharma

2

类似这样的事情在某些浏览器上无法正常工作,通常是由于以下原因:

window.document.body.scrollTop++;

您不能这样做,因为一些浏览器将该值作为字符串,例如"5px",而有些则将其作为数字。


1

解决EDGE问题需要设置scrollTop on scrollingElement文档属性:

document.scrollingElement.scrollTop= x; // x is integer value

但是您必须确保HTML元素上的CSS设置了overflow的默认值(visible):
html {
    overflow: visible;
}

-1
如果您需要在IE和Edge中运行它:
document.body.scrollTop = x

1
不存在IE Edge这样的东西。 - TylerH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接