你没设置取出来是空, 可以这样:getPos:function(o){//取元素坐标 var x = 0, y = 0; do{ x += o.offsetLeft; y += o.offsetTop; }while(o=o.offsetParent); return {'top':x,'left':y}; } var tb=document.getElementById("tbName"); alert(getPos(tb).top);
用style.top只能取到你事先在CSS中定义过的值,你没有定义过,就是null用这个取//获取元素样式 //id 页面对象或其ID //style 样式名称 eg:"padding-left","z-index","top","width" ... function getStyle(id,style) { element = $(id); var value = element.style[style] if (!value) { if(document.defaultView && document.defaultView.getComputedStyle) //FF { var css = document.defaultView.getComputedStyle(element, null) value = css ? css.getPropertyValue(style) : null } else if(element.currentStyle) //IE { value = element.currentStyle[ReWriteStyleName(style)] } } if(window.opera && ['left', 'top', 'right', 'bottom'].include(style)) if(getStyle(element, 'position') == 'static') value = 'auto' value == 'auto' ? null : value return value }//IE时重写样式名称 eg:z-index→zIndex; function ReWriteStyleName(str) { var oStringList = str.split('-'); if (oStringList.length == 1) { return oStringList[0]; } var camelizedString =(str.indexOf('-') == 0)?oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1):oStringList[0]; for (var i = 1; i <oStringList.length;i++) { var s = oStringList[i]; camelizedString += s.charAt(0).toUpperCase() + s.substring(1); } return camelizedString; }
alert((document.getElementById("info_pos").offsetTop));
可以这样:getPos:function(o){//取元素坐标
var x = 0, y = 0;
do{
x += o.offsetLeft;
y += o.offsetTop;
}while(o=o.offsetParent);
return {'top':x,'left':y};
}
var tb=document.getElementById("tbName");
alert(getPos(tb).top);
//id 页面对象或其ID
//style 样式名称 eg:"padding-left","z-index","top","width" ...
function getStyle(id,style)
{
element = $(id);
var value = element.style[style]
if (!value)
{
if(document.defaultView && document.defaultView.getComputedStyle) //FF
{
var css = document.defaultView.getComputedStyle(element, null)
value = css ? css.getPropertyValue(style) : null
}
else if(element.currentStyle) //IE
{
value = element.currentStyle[ReWriteStyleName(style)]
}
} if(window.opera && ['left', 'top', 'right', 'bottom'].include(style))
if(getStyle(element, 'position') == 'static') value = 'auto'
value == 'auto' ? null : value
return value
}//IE时重写样式名称 eg:z-index→zIndex;
function ReWriteStyleName(str)
{
var oStringList = str.split('-');
if (oStringList.length == 1)
{
return oStringList[0];
}
var camelizedString =(str.indexOf('-') == 0)?oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1):oStringList[0];
for (var i = 1; i <oStringList.length;i++)
{
var s = oStringList[i];
camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
}
return camelizedString;
}