查看滚动条的滚动距离
window.pageXOffset/pageYOffset
document.body/documentElement.scrollLeft/scrollTop
- 兼容值比较混乱,用时取两个值相加,因为不可能存在两个同时有值
- IE8及IE8以下的浏览器
- document.body.scrollLeft/Top ie8 ie5 ie4
- document.documentElement.scrollLeft/Top ie7 ie6
- 封装兼容性方法,求滚动轮滚动距离getScrollOffset()
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
}
}
}
查看视图的尺寸
window.innerWidth/innerHeight : IE及IE8以下不兼容
document.documentElement.clientWidth/clientHeight : 标准模式下,任意浏览器都兼容;html头部添加 <!DOCTYPE html> ,即为标准模式
document.body.clientWidth/clientHeight : 适用于怪异模式下的浏览器,
- 封装兼容性方法,返回浏览器视图尺寸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
}
}
}
}
查看元素的几何尺寸
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
- 封装方法,返回元素相对于文档的坐标
getElementPosition ;
function getElementPosition(element) {
if (!element || !element.offsetLeft) return null;
var actualLeft = element.offsetLeft,
actualTop = element.offsetTop,
current = element.offsetParent; // 取得元素的offsetParent
while (current !== null) {
actualLeft += current.offsetLeft;
actualTop += current.offsetTop;
current = current.offsetParent;
}
return {
left: actualLeft,
top: actualTop
};
}
让滚动条滚动
- window上有三个方法:
scroll();, scrollTo();, scrollBy();
- 三个方法功能类似,用法都是将x,y坐标传入。即实现让滚动轮滚动到当前位置。
- 区别:
scrollBy() 会在之前的数据基础之上做累加
- 利用scrollBy()快速阅读的功能
var start = document.getElementsByTagName('div')[0];
var stop = document.getElementsByTagName('div')[1];
var timer = 0;
var key = true;
start.onclick = function () {
if (key) {
timer = setInterval(function () {
window.scrollBy(0, 10);
}, 100)
key = false;
}
}
stop.onclick = function () {
clearInterval(timer);
key = true;
}
脚本化CSS
- dom.style.prop
- 可读写行间样式,没有兼容性问题,碰到float这样的保留字属性,前面应加css
- float -> cssFloat
- 复合属性必须拆解,组合单词变成小驼峰式写法
- 写入的值必须是字符串格式
- 查询计算样式
window.getComputedStyle(ele,null); null可以表示伪元素
- 计算样式只读
- 返回的计算样式的值都是绝对值,没有相对单位
- IE8及IE8以下不兼容
- 查询样式
- ele.currentStyle
- 计算样式只读
- 返回的计算样式的值不是经过转换的绝对值
- IE独有的属性
- 封装兼容性方法
getStyle(ele,prop);
function getStyle(elem, prop) {
if (window.getComputedStyle) {
return window.getComputedStyle(elem, null)[prop]
} else {
return elem.currentStyle[prop];
}
}