所有现代浏览器均支持以下3个属性:offsetParent,offsetLeft,offsetTop
不同点在于有的浏览器的offsetParent是直接指向根节点的,有的不是
function pageX(elem){
//查看是否位于根元素
return elem.offsetParent?elem.offsetLeft + pageX(elem.offsetParent):elem.offsetLeft;
}
function pageY(elem){
return elem.offsetParent?elem.offsetTop + pageY(elem.offsetParent):elem.offsetTop;
}
获取相对于父元素的位置
function parentX(elem){
return elem.parentNode == elem.offsetParent?elem.offsetLeft:pageX(elem)-pageX(elem.parentNode);
}
function parentY(elem){
return elem.parentNode == elem.offsetParent?elem.offsetTop:pageY(elem)-pageY(elem.parentNode);
}
获取相对于CSS容器的位置
function cssX(elem){
return parseInt(getStyle(elem,"left"));
}
function cssY(elem){
return parseInt(getStyle(elem,"top"));
}
获取隐藏元素的高度
//获取隐藏元素的高度和宽度
function fullHeight(elem) {
if(getStyle(elem,"display") != "none") {
return elem.offsetHeight || getHeight(elem);
}
var old = resetCss(elem, {
display:"",
visibility:"hidden",
position:"absolute"
});
var h = elem.offsetHeight || getHeight(elem);
restoreCss(elem,old);
return h;
}
function resetCss(elem,prop) {
var old = {};
for(var i in prop) {
old[i] = elem.style[i];
elem.style[i] = prop[i];
}
return old;
}
function restoreCss(elem,old) {
for(var i in prop) {
elem.style[i] = old[i];
}
}