简体   繁体   中英

!doctype html ruins my script

So I have following code which has to return screen coordinates of given object:

<!DOCTYPE HTML>
<html>
<head>
</head>
<body style="margin:0px;padding:0px;">

<div id="help" style="top:100px;right:100px;height:200px;width:200px;position:fixed;border:1px solid #000"></div>
<div id="what">what</div>
<div style="position:relative;margin-top:10000px;"></div>
<script>

function getoffset(element) {
    var xPosition = 0;
    var yPosition = 0;

    while(element) {
        yPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
        xPosition += (element.offsetTop - element.scrollTop + element.clientTop);
        element = element.offsetParent;
    }
    return [xPosition, yPosition];
}

function cl(){
    var help = document.getElementById('help');
    var what = document.getElementById('what');
    var where = getoffset(what);
    help.innerHTML= where;

}
setInterval(function (){cl()},100);
</script>
</body>

And it works fine on IE,chrome,opera and ff until I add <!DOCTYPE HTML> directive(to force IE to respect div positioning).
When I do that this code returns the same values whole the time(only Chrome doing fine). What I'm doing wrong??

You are using some HTML or javascript which depends on the browser being in quirks mode to function (IE9+ also has an "IE8 standards mode"). Adding a valid modern doctype makes the browser be in standards/strict mode.

The problem probably is your use of scrollLeft / scrollRight and scrollTop / clientTop . They behave differently in older browsers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM