JS——scroll封装
DTD未声明:document.body.scrollTop
DTD已声明:document.documentElement.scrollTop
火狐谷歌IE9:window.pageYOffset
compatMode:可以判断是否声明DTD,CSS1Compat是,BackCompat否
复杂版本:
<script> window.onscroll = function () { console.log(scroll().left + " " + scroll().top); } function scroll() { if (window.pageYOffset) { return { "top": window.pageYOffset, "left": window.pageXOffset }; } else if (document.compatMode == "CSS1Compat") { return { "top": document.documentElement.scrollTop, "left": document.documentElement.scrollLeft }; } else { return { "top": document.body.scrollTop, "left": document.body.scrollLeft }; } } </script>
简单版本:
<script> window.onscroll = function () { console.log(scroll().left + " " + scroll().top); } function scroll() { return { "top": window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop, "left": window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft }; } </script>