有如下元素:
<div id="div1" >div1</div>
#div1{
100px;
height:100px;
position:absolute;
left:0;
top:0;
background: red;
}
js擷取:
var xpos=parseInt(elem.style.left);
var ypos=parseInt(elem.style.top);
得到的xpos為Nan,為什麼?
擷取css 設定的style值
需要使用 document.defaultView..getComputedStyle(node, null).getPropertyValue(styleString) //w3c方法
其中node為你要查詢的節點對象 styleString為 如'top' 或'background-color' 此類屬性名 而不是js中的backgroundColor 之類的
ie的話 用 node.currentStyle[styleString] 但這個styleString 要用 'backgroundColor' 這種格式取
記得 如果你沒有 在node.style.屬性名='' 這樣顯式的在js中指派或内聯style指派, 你用node.style. 是取不到值的 必須使用上面的方法。
上面的改成:
elem=document.getElementById('id');
var xpos= document.defaultView.getComputedStyle(elem,null).getPropertyValue('left');
var ypos= document.defaultView.getComputedStyle(elem,null).getPropertyValue('top');
var xpos=parseInt(xpos);
var ypos=parseInt(ypos);
就可以了。