1 窗口尺寸
1.1 常用属性
window.innerWidth //当前窗口宽度
window.innerHeight //当前窗口高度
//封装返回浏览器视口尺寸
function getViewportOffset() {
if(window.innerHeight) {
return {
w : window.innerWidth,
h : window.innerHeight
}
} else if(document.documentElement.clientHeight) {
return {
w : document.documentElement.clientWidth,
h : document.documentElement.clientHeight
}
} else if(document.compatMode === "BackCompat") {
debugger
return {
w : document.body.clientWidth,
h : document.body.clientHeight
}
} else {
}
}
document.body.scrollLeft + document.documentElement.scroll
互相冲突,可以相加配合使用,一个若有值,另一个必然为0。
1.2 混杂模式和标准模式
若document.compatMode == "CSS1Compat"
,那么当前处于标准模式,若document.compatMode =="BackCompat"
,那么当前处于混杂模式
混杂模式是HTML头部没有<!DOCTYPE html>
或者第一行有其它字符
1.3 滚动条
//封装返回滚动条距离,兼容各种浏览器
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
}
}
}
1.4 dom对象坐标
- getBoundingClientRect 返回一个对象,里面包括宽高left top坐标信息
- offsetWidth dom对象宽度
- offsetHeight dom对象高度
- offsetTop dom对象相对于父级或文档的左边距离
- offsetLeft dom对象相对于父级或文档的上边距离
对于无定位父级的元素,返回相对于文档的坐标。对于有定位父级的元素,返回相对于最近的有定位的父级的坐标
position:static;
可以让当前dom对象变成无定位元素
offsetParent
返回最近的有定位的父级,若无,返回body,body.offsetParent = null;
// 求元素相对于文档的坐标
function getElementPosition(elem) {
var sumLeft = 0,
sumTop = 0;
while(elem.offsetParent != null) {
sumLeft += elem.offsetLeft;
sumTop += elem.offsetTop;
elem = elem.offsetParent;
}
return {
"Left" : sumLeft,
"Top" : sumTop
}
}
1.5 滚动条滚动
//实现自动翻页
var timer ;
div.onclick = function() {
if(timer == undefined) {
timer = setInterval(function() {
scrollBy(0, 10);
}, 50);
}
}
div1.onclick = function() {
if(timer != undefined) {
clearInterval(timer);
timer = undefined;
}
}
2 编辑CSS样式
dom.style.prop
只能编辑行间样式的CSS,并没有兼容性问题,如果遇到保留字属性,前缀加css,规则遵循小驼峰;
float-->cssFloat
写入的值为字符串格式
window.getComputedStyle(ele, null);
第二个null实际可获取伪元素的值。该方法返回的都是绝对值,没有相对值
IE8及以下不兼容
查询样式
ele.currentStyle 返回的值不是经过转换的绝对值,是IE独有属性
//封装兼容性方法
function getStyle(ele, prop) {
if(window.getComputedStyle) {
return window.getComputedStyle(ele, null)[prop];
} else {
return ele.currentStyle[prop];
}
}