码迷,mamicode.com
首页 > Windows程序 > 详细

scrollWidth,clientWidth,offsetWiddth,innerWinth 元素定位

时间:2016-01-27 14:38:51      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

getBoundingClientRect()方法。它返回一个对象,其中包含了left、right、top、bottom四个属性,分别对应了该元素的左上角和右下角相对于浏览器窗口(viewport)左上角的距离。

通用的获得元素相对于viewPort的函数,一直向上遍历父元素(因为有些浏览器不支持getBoundingClientRect方法的):
function getElementLeft(element) {
var actualLeft = element.offsetLeft;
var current = element.offsetParent;

while (current !== null) {
actualLeft += current.offsetLeft;
current = current.offsetParent;
}
return actualLeft;
}

function getElementTop(element) {
var actualTop = element.offsetTop;
var current = element.offsetParent;

while (current !== null) {
actualTop += current.offsetTop;
current = current.offsetParent;
}
return actualTop;
}

function getBoundingClientRect(element) {

var scrollTop = document.documentElement.scrollTop;
var scrollLeft = document.documentElement.scrollLeft;

if (element.getBoundingClientRect) {
if (typeof arguments.callee.offset != “number”){ //修复ie8以及之前版本从(2,2)坐标开始计算
var temp = document.createElement(“div”);
temp.style.cssText = “position:absolute;left:0;top:0;”;
document.body.appendChild(temp);
arguments.callee.offset = -temp.getBoundingClientRect().top - scrollTop;
document.body.removeChild(temp);
temp = null;
}
var rect = element.getBoundingClientRect();
var offset = arguments.callee.offset;
return {
left: rect.left + offset,
right: rect.right + offset,
top: rect.top + offset,
bottom: rect.bottom + offset
};
} else { //对于不支持getBoundingClientRect的修复
var actualLeft = getElementLeft(element);
var actualTop = getElementTop(element);

return {
left: actualLeft - scrollLeft,
right: actualLeft + element.offsetWidth - scrollLeft,
top: actualTop - scrollTop,
bottom: actualTop + element.offsetHeight - scrollTop
}
}
}
因为使用了arguments.callee,因此在strict mode下用不了

scrollWidth,clientWidth,offsetWiddth,innerWinth 元素定位

标签:

原文地址:http://www.cnblogs.com/chuangweili/p/5163065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!