html元素elem.style.top.left始终为空
2014-08-28 20:32 youxin 阅读(1138) 评论(0) 收藏 举报有如下元素:
<div id="div1" >div1</div>
#div1{
    width: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);
就可以了。
 
                    
                 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号