如何使用javascript获取像素中左/右/上/下属性的值

How to get values of left/right/top/bottom properties in pixel using javascript?

本文关键字:属性 javascript 何使用 获取 像素      更新时间:2023-09-26

我需要获得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>

使用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>