我需要获取#test
中px
的左/右/上/下属性。我的js代码将属性值赋予auto
。如何获取px
中的值?
<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
};
答案 0 :(得分: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>
答案 1 :(得分: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);
};
&#13;
#test{
position: absolute;
}
&#13;
<div id="test">
<p>Dummy text</p>
</div>
&#13;