2016-04-29 22 views
1

我需要得到#test的左/右/上/下屬性px。我的js代碼給出的屬性值爲auto。如何獲得px的價值?如何使用javascript獲取像素中左/右/上/下屬性的值?

<div id="test"> 
    <p>Dummy text</p> 
</div> 
#test{ 
    position: absolute; 
} 
window.onload = function(){ 
    var test = document.getElementById("test"); 
    var left = window.getComputedStyle(test).getPropertyValue("left"); 
    console.log(left); // auto 
}; 

回答

1

使用此代碼

window.onload = function(){ 
 
    var test = document.getElementById("test"); 
 
    
 
    var left = test.offsetLeft; 
 
    var right = test.offsetWidth - left; 
 
    var top = test.offsetTop; 
 
    var bottom = test.offsetHeight - top; 
 
    
 
    document.write("Left:" + left + "//"); 
 
    document.write("Right:" + right + "//"); 
 
    document.write("Top:" + top + "//"); 
 
    document.write("Bottom:" + bottom); 
 
};
#test{ 
 
    position: absolute; 
 
}
<div id="test"> 
 
    <p>Dummy text</p> 
 
</div>

1

使用offsetLeft代替

test.offsetLeft

window.onload = function(){ 
 

 
    var test = document.getElementById("test"); 
 

 
    document.write(test.offsetLeft); // auto 
 
};
#test{ 
 
    position: absolute; 
 
}
<div id="test"> 
 
    <p>Dummy text</p> 
 
</div>

相關問題