【问题标题】:How to get values of left/right/top/bottom properties in pixel using javascript?如何使用javascript获取像素中左/右/上/下属性的值?
【发布时间】:2016-10-16 04:35:13
【问题描述】:

我需要在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
};

【问题讨论】:

    标签: javascript html css css-position


    【解决方案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>

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-02
        • 2015-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多