DOM操作
查看滚动条的滚动距离(IE9以下不兼容)
window.pageXOffset/pageYOffset//(按比例计算)
//兼容IE
document.body/documentElement.scrollLeft/scrollTop
封装兼容IE滚动条的距离
//封装兼容IE滚动条的距离
// 获取滚动条的距离
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/ innerHeigh(IE9以下不兼容)
//标准模式下,任意浏览器都兼容
document.documentElement.clientWidth/clientHeigh
//兼容IE 怪异模式下的浏览器兼容
document.body.clientWidth/clientHeight
//判断浏览器是否是怪异模式
document.compatMode
return:"CSS1Compat"标准模式
: "BackCompat"怪异模式
封装兼容IE视口的尺寸
//封装兼容IE视口的尺寸
function getinnerWH() {
if (window.innerHeight) {
return {
width: window.innerWidth,
hight: window.innerHeight,
}
} else {
if (window.document.compatMode == 'BackCompat') {
return {
width: document.body.clientWidth,
hight: document.body.clientHeight,
}
} else if (window.document.compatMode == 'CSS1Compat')
return {
width: document.documentElement.innerWidth,
hight: document.documentElement.innerHeight,
}
}
}
查看元素几何尺寸
DOM对象.getBoundingClientRect(); 返回值为一个对象
对象中包括left right bottom top ;
left和 top代表该元素左上角的x和y坐标,right和bottom代表元素右下角的x和y坐标
获取的内容不是实时获取的
查看元素尺寸
DOM对象.offsetWidth/offsetHeight//(视觉上的尺寸,包含padding 不包括margin)
查看元素的位置
DOM对象.offsetLeft DOM对象.offsetHeight
相对于无定位的元素,返回相对于文档坐标
相对于有定位父级的元素,返回相对于最近有定位的父级的坐标
//封装获取元素位置
function getElementPosition(ele) {
// 当浏览器支持getBoundinClientRect方法
if (ele.getBoundingClientRect && 0) {
var pos = ele.getBoundingClientRect();
// console.log(pos.left + getScrollOffset().x);
return {
x: pos.left + getScrollOffset().x,
y: pos.top + getScrollOffset().y
}
} else {
var pos = {
'top': 0,
'left': 0
};
var _ele = ele;
if (ele.offsetParent) {
while (ele.offsetParent) {
if (_ele == ele) { /
pos.top += ele.offsetTop;
pos.left += ele.offsetLeft;
ele = ele.offsetParent;
} else {
pos.top += ele.offsetTop + parseFloat(window.getComputedStyle(ele).borderWidth);
pos.left += ele.offsetLeft + parseFloat(window.getComputedStyle(ele).borderWidth);
ele = ele.offsetParent;
}
}
}
return {
x: pos.left,
y: pos.top
}
}
}