查看滚动条的滚动距离
- window.pageXOffset/pageYOffset // IE8及IE8以下不兼容
- document.body/documentElement.scrollLeft/scrollTop
兼容性比较混乱,用时取两个值相加,因为不可能存在两个同时有值 - 封装兼容性方法,求滚动条滚动距离getScrollOffset()
<script>
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.scrollTtop
}
}
}
</script>
查看视口的尺寸
- window.innerWidth/innerHeight // IE8及IE8以下不兼容
- document.documentElement.clientWidth/clientHeight // 标准模式下,任意浏览器都兼容
- document.body.clientWidth/clientHeight // 适用于怪异模式下的浏览器
- 封装兼容性方法,返回浏览器视口尺寸getViewportOffset()
<script>
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
}
}
}
}
</script>
查看元素的几何尺寸
- domEle.getBoundingClientRect();
- 兼容性很好
- 该方法返回一个对象,对象里面有left, top, right, bottom 等属性。left 和 top 代表该元素左上角的X和Y坐标,right 和 bottom代表元素右下角的X 和Y坐标
- height 和 width 属性老版本IE并未实现
- 返回的结果并不是实时的。
查看元素的尺寸
- dom.offsetWidth, dom.offsetHeight
查看元素的位置
-
dom.offsetLeft, dom.offsetTop
对于无定位父级的元素,返回相对文档的坐标。对于有定位父级的元素,返回相对于最近的有定位的父级的坐标 -
dom.offsetParent
返回最近的有定位的父级,如无,返回body, body.offsetParent返回null -
求元素相对于文档的坐标 getElementPositon
让滚动条滚动
- window上有三个方法
- scroll() scrollTo() scrollBy()
- 三个方法功能类似,用法都是将X,Y坐标传入。即实现让滚动条滚动到当前位置。
- 区别: scrollBy()会在之前的数据基础之上做累加,即传入的是滚动多少的距离
- 利用scrollBy() 快速阅读的功能
脚本化CSS
读写元素CSS属性
- dom.style.prop
- 可读写行间样式,没有兼容性问题,碰到float这样的保留字属性,前面应加css
- float --> cssFloat
- 复合属性最好拆解,组合单词变成小驼峰式写法
- 写入的值必须是字符串格式
查询计算样式
- window.getComputedStyle(ele,null);
- 后面的null,是填写伪元素的,用来获取伪元素样式 例如:
window.getComputedStyle(div,"after").width
- 计算样式只读
- 返回的计算样式的值都是绝对值,没有相对单位
- IE8 及 IE 8 以下不兼容
- 后面的null,是填写伪元素的,用来获取伪元素样式 例如:
查询样式
- ele.currentStyle
- 计算样式只读
- 返回的计算样式的值不是经过转换的绝对值
- IE独有的属性
封装兼容性方法getStyle(elem,prop)
<script>
function getStyle(elem,prop){
if(window.getComputedStyle) {
return window.getComputedStyle(elem,null)[prop];
}else{
return elem.currentStyle[prop];
}
}
</script>