1. Check the scrolling distance of the scroll bar
window.pageXOffset
The right side of the screen, for example how many pixels are on the left side of the web page
window.pageYOffset
The bottom of the screen, how many pixels away from the top of the page
Disadvantage : IE9 and below are not compatible
How to get scrolling pixels below IE9?
document.body.scrollLeft
document.body.scrollTop
document.documentElement.scrollLeft
document.documentElement.scrollTop
The compatibility of document.body and document.documentElement is confusing,
When document.body can be obtained, document.documentElement must be 0,
When document.documentElement can be obtained, document.body must be 0
So when using it, it is often used like this:
document.body.scrollLeft + document.documentElement.scrollLeft
Small exercise : Encapsulate a getScrollOffset() method to solve compatibility problems, so that all versions of browsers support it.
//The compatible version asks the scrolling distance of the browser scroll bar function getScrollOffset() { if(window.pageXOffset) { return { x : window.pageXOffset, y : window.pageYOffset } }else { return { x : document.body.scrollLeft + document.documentElement.scrollLeft, y : document.body.scrollTop + document.documentElement.scrollTop, } } }
2. View the size of the viewable window (pixels)
window.innerWidth / window.innerHeight
You can view the currently visible pixels of the screen, not the screen size.
Disadvantage: Not compatible with IE9 and below
document.documentElement.clientWidth
document.documentElement.clientHeight
In standard mode, any browser supports it.
document.body.clientWidth
document.body.clientHeight
For browsers in quirks mode
(For example, in the h5 document, deleting the document type declaration is a weird mode...)
Encapsulate a method to return the size of the browser visualization window getViewportOffset() to solve the compatibility problem.
function getViewportOffset() { if(window.innerWidth) { return { w : window.innerWidth, h : window.innerHeight } }else { if(document.compatMode === 'BackCompat'){ w : document.body.clientWidth; h : document.body.clientHeight } else { return { w : document.documentElement.clientWidth, h : document.documentElement.clientHeight } } } }
Check the width and height of the element
dom.offsetWidth
dom.offsetHeight
<style type="text/css"> #only{ background-color: red; width: 100px; height: 100px; } </style> <body> <div id="only"></div> <script type="text/javascript"> var div = document.getElementsByTagName('div')[0]; </script> </body>
控制台测试:
可以获取元素的宽高。
查看元素的位置
dom.offsetLeft , dom.offsetTop
返回相对于与自己最近的有定位的父级元素的位置信息,
如果没有定位的父级元素,则相对于body的坐标。
返回最近的有定位的父级
dom.offsetParent
返回最近的有定位的父级,如果没有,返回body,body.offsetParent返回null
让滚动条滚动
widow上的三个方法
scroll(x,y),scrollTo(x,y)
这两个方法效果一样,小括号里填写的参数为xy为x轴和y轴,要滚到到多少像素的地方
scrollBy(x,y)
小括号里填写的参数为xy为x轴和y轴,要滚动多少像素。填写负数为反方向。