I am new to JavaScript.I'm try to write a float layer. The following code is work on non HTML5
<html>
<body onl oad="initSession()">
<div id="demo"></div>
<div id="flotLayer" style="position:absolute;width:60px;height:60px;z-index:30;visibility:hidden;right: 10px;top:0px;">
<div style="width:100px; height:100px; border:solid 1px #cccccc">floatLayer</div>
</div>
<div style="width:100px; height:5000px;"></div>
<script>
setInterval(() => {
myTimer()
}, 50);
setInterval(MoveLayer, 50);
function myTimer() {
const d = document.getElementById('flotLayer').style.top;
document.getElementById("demo").innerHTML = d;
}
function initSession() {
document.getElementById('flotLayer').style.visibility = 'visible';
MoveLayer();
myTimer();
}
function MoveLayer() {
var x = 50;
var y = 250;
var _y = document.body.scrollTop y;
var diff =(_y - parseInt(document.getElementById('flotLayer').style.top))*.50;
var rey=_y-diff;
document.getElementById('flotLayer').style.top=rey.toString() "px";
document.getElementById('flotLayer').style.right=x.toString() "px";
}
</script>
</body>
</html>
But when I declare HTML5 Doctype <!DOCTYPE html>
The timer look like only run one time.Can anyone give me some hints?
The symptom to look for when replicating this is that scrolling the page down, with the doctype the floatLayer
scrolls off the top of the page. Without a doctype, it moves up but then is moved back down to be centered vertically.
CodePudding user response:
Some debugging shows that with the doctype, document.body.scrollTop
is always 0
, but without it, it grows as the page is scrolled upward.
Different rendering engines had different approaches to whether the main page scroll is scrolling the body
element or the html
element. Apparently changing the doctype changes Chromium-based browsers from scrolling body
to scrolling html
.
To make it work regardless of which one is scrolled, use the one that's non-zero:
var _y = (document.body.scrollTop || document.documentElement.scrollTop) y;