本文介绍了为什么窗口onscroll事件不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行窗口onscroll事件,但是我不知道为什么它不能在所有浏览器(firefox,chrome等)上都起作用,并且没有发生错误.

I want to execute the window onscroll event, but I don't know why it doesn't work on all browsers(firefox, chrome, etc), and there is no errors occurred.

完整代码:

var elem = document.getElementById('repeat');
var show = document.getElementById('show');

for (i = 1; i <= 300; i++) {
    elem.innerHTML += i + "<br/>";
}


window.onscroll = function () {
    show.innerHTML = document.body.scrollTop;
};
#show {
    display:block;
    position:fixed;
    top:0px;
    left:300px;
}
<pre id="repeat"></pre>

<div style="position:relative;">
    <div id="show">x</div>
</div>

也jsfiddle: http://jsfiddle.net/sqo0140j

Also jsfiddle:http://jsfiddle.net/sqo0140j

出了什么问题?

推荐答案

您说了一些有趣的事情:

You said something interesting:

代码中唯一可能发生的方法是onscroll功能块进行更改,因为HTML设置了x.

The only way in your code that can happen is if the onscroll function block makes a change because your HTML sets x.

如果您确实触发了window.onscroll = function(),但是您没有获得正确的滚动位置(即0),请尝试更改返回滚动位置的方式:

If your window.onscroll = function() is indeed firing, but you are not getting the right scroll position (i.e. 0), try changing the way the scroll position is returned:

window.onscroll = function () {
    show.innerHTML = document.documentElement.scrollTop || document.body.scrollTop;
};

我发现document.documentElement.scrollTop在Chrome上始终返回0.这是因为WebKit使用body来跟踪滚动,而Firefox和IE使用html.

I found out that document.documentElement.scrollTop always returns 0 on Chrome. This is because WebKit uses body for keeping track of scrolling, but Firefox and IE use html.

请尝试更新的代码段:

var elem = document.getElementById('repeat');
var show = document.getElementById('show');

for (i = 1; i <= 300; i++) {
    elem.innerHTML += i + "<br/>";
}


window.onscroll = function () {
    show.innerHTML = document.documentElement.scrollTop || document.body.scrollTop;
};
#show {
    display:block;
    position:fixed;
    top:0px;
    left:300px;
}
<pre id="repeat"></pre>

<div style="position:relative;">
    <div id="show">x</div>
</div>

这篇关于为什么窗口onscroll事件不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-12 00:01