获取元素绝对位置 position


if(!window.console){
window.console = {};
window.console.log = function(){};
}
/**
* @description 获取元素在页面的绝对位置。可以凑合着用。
* @author shawn 2012-02-17
* @param {String|HtmlElement} el DOM元素或者是id
* @return {Object} {left:offsetLeft,top:offsetTop}
* BUG:如果元素在table中,计算稍微有点问题。
*/
var getPosition = function(el){
var self = arguments.callee;
if(!self.init){
var ua = navigator.userAgent;
if(/MSIE ([^;]+)/.test(ua)){
self.isIE = true;
self.ieVer = parseInt(RegExp.$1);
}
self.getStylePro = function(target,property){
if(self.isIE){
if(property == 'float'){
property = 'styleFloat';
}
return target.currentStyle[property];
}else{
if(property == 'float'){
property = 'cssFloat';
}
return document.defaultView.getComputedStyle(target,null)[property];
}
};
self.init = true;
}

var top = 0,left = 0,
p = el.offsetParent;
var floatNd = null;

var bdLeft = 0,
bdTop = 0;
if(p){
do{
var tagName = p.tagName.toUpperCase();
console.log("P: " + p.tagName);
if(self.isIE && self.ieVer < 8){
if(tagName== 'BODY' || tagName== 'HTML'){

}else{
var fl = self.getStylePro(p,'float');
var pos = self.getStylePro(p,'position');
console.log('pos:' + pos )
if('#left#right'.indexOf('#' + fl) != -1){
floatNd = p;
}else if("#TABLE#THEAD#TBODY#TH#TR#TD".indexOf('#'+tagName) == -1){
top += p.offsetTop;
left += p.offsetLeft;
}
if('#relative#absolute#fixed'.indexOf('#'+pos) != -1){
bdLeft = self.getStylePro(p,'borderLeftWidth');
bdTop = self.getStylePro(p,'borderTopWidth');
top += isNaN(parseInt(bdTop,10)) ? 0 : parseInt(bdTop,10);
left += isNaN(parseInt(bdLeft,10)) ? 0: parseInt(bdLeft,10);
}
}
}else{
if("#TABLE#THEAD#TBODY#TH#TR#TD".indexOf('#'+tagName) == -1){
top += p.offsetTop;
left += p.offsetLeft;
}
if(!self.isIE && /Opera/.test(navigator.userAgent) == false){
bdLeft = self.getStylePro(p,'borderLeftWidth');
bdTop = self.getStylePro(p,'borderTopWidth');
top += parseInt(bdTop,10);
left += parseInt(bdLeft,10);
}

}
}while(p = p.offsetParent);
}


var offset = getOffset(el);
if(floatNd){
console.log('float')
left += (floatNd.offsetLeft+2);
top += (floatNd.offsetTop+2);
if(self.isIE && self.ieVer < 8){
left -= 2;
top -= 2;
}
}
return {'x':(left+offset.left),'y':(top+offset.top)};
}

你可能感兴趣的:(JavaScript)