Why does the window onscroll event not work?

I want to execute the window event onscroll, but I don’t know why it does not work in all browsers (firefox, chrome, etc.), and there were no errors.

Full code:

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>
Run codeHide result

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

What is the problem?

+4
source share
3 answers

You said something interesting:

x is changed to 0 and stays as it is.

The only way in your code that can happen is to use a function block onscrollbecause your HTML sets x.

window.onscroll = function() , (.. 0), :

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

, document.documentElement.scrollTop 0 Chrome. , WebKit body , Firefox IE 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>
Hide result
+6

document.body.scrollTop; Chrome Opera, Firefox 0.

Viceversa document.documentElement.scrollTop; Firefox, Chrome Opera...

, document.body.scrollTop; FF

:

:

Math.max(document.body.scrollTop, document.documentElement.scrollTop);

 document.body.scrollTop || document.documentElement.scrollTop;

.

0

, , onscroll.

datacontainer, , . , -. :

. , overflow: auto .

: auto, onscroll.

0

All Articles