DOM基本操作1
~查看滚动条的滚动距离
1. windows.pageXOffset/pageYOffset
IE8及IE8以下不兼容
2. document.body/documentElement.scrollLeft/scrollTop
兼容性比较混乱,用时取两个值相加,因为不可能存在两个同时有值
3. 封装兼容性方法,求滚动轮滚动离getScrollOffset()
~查看视口的尺寸
1.window.innerWidth/innerHeight
IE8及IE8以下不兼容
2.document.documentElement.clientWidth/clientHeight
标准模式下,任何浏览器都兼容
3.docunment.body.clientWidth/clientHeight
适用怪异模式下的浏览器
4.封装兼容性方法,返回浏览器视口尺寸getViewportOffset()
function getViewportOffset() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight
}
} else {
if (document.compatMode === "BackCompat") {
return {
w: document.body.clientWidth,
h: document.body.clientHeight
}
} else {
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
}
}
}
~查看元素的几个属性
1.domEle.getBoundingClienRect();
2.兼容性很好
3.该方法返回一个对象,对象里面有left,top,right,bottom等属性。left和top代表该元素左上角的X和Y坐标,right和bottom代表元素右下标的X和Y坐标
4.height和width属性老版本IE并未实现
5.返回的结果并不是"实时的"
~查看元素的尺寸
1.dom.offsetWidth,dom.offsetHeight
~查看元素的位置
1.dom.offsetLeft,dom.offsetTop
2.对于无定义父级的元素,返回相对文档的坐标。对于有定位父级的元素,返回相对于最近的有定位和父级的坐标。
3.dom.offsetParent
4.返回最近的有定位父级,如无,返回body,body.offsetParent返回null
5.eg:求元素相对于文档的坐标getElementPosition
~让滚动条滚动
1.让滚动条滚动
window上有三个方法
scroll(),scrollTO(),scrollBy();
三个方法用法类似,用法都是将x,y坐标传入。即实现让滚动轮滚动到当前位置。
区别:
scroll和scrollTo两个没有差别。
scrollBy()会在之前的数据基础上做累加。
eg:利用scroll()快速阅读的功能。