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

时间:2016-04-29 13:46:47

标签: javascript html css css-position

我需要获取#testpx的左/右/上/下属性。我的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
};

2 个答案:

答案 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)

使用此代码

&#13;
&#13;
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;
&#13;
&#13;