我需要在 px
中获取 #test
的左/右/上/下属性。我的 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
};
最佳答案
使用此代码
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>
关于javascript - 如何使用 javascript 获取像素中左/右/上/下属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36940056/