Javascript - window.getComputedStyle 返回“auto”作为元素顶部和左侧的属性

jay*_*Son 5 html javascript css jquery

在我的网页上,我有一些元素(div、子 div、按钮等),它们的位置是相对于它们所在的 div 生成的,并且彼此之间。这导致使用window.getComputedStyle 时topleft属性不是数字值,而只是“auto”,而宽度高度以 px 为单位。

我需要绝对值用于测量目的的问题,所以我想知道是否有办法以某种方式获取它们。我希望window.getComputedStyle会做,但显然它不会。

下面有一个例子,没有任何格式,但同样的问题。

如果有 jQuery 解决方案,我当然也会很感激。

亲切的问候,
杰森

<html>

<head>
  <title>Test</title>
  <script type="text/javascript">
    function test() {
      var style = window.getComputedStyle(document.getElementsByTagName("button")[0]);
      alert(
        "top = " + style.top + //auto
        "\nleft = " + style.left + //auto
        "\nwidth = " + style.width + //63px
        "\nheight = " + style.height //24px
      );
    }
  </script>
</head>

<body>
  <div>
    <button id="buttonTest" onClick="test()">Test it!</button>
  </div>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

Edg*_*hez 5

getComputedStyle 方法返回CSS 属性的解析值。

如果样式表作者(您)没有指定某些 CSS 属性的值(即:顶部、右侧、底部和左侧),则返回的解析值将是默认值。这些CSS属性都有一个默认值“auto”。

如果您不能或不想在样式表中自己指定值,并且只需要相对于视口左上角的坐标,请考虑使用Element.getBoundingClientRect()

<html>
<head>
    <title>Test</title>
    <style>
        /* Remove default styling to ensure a top and left value of 0 */
        body {margin:0; padding:0}
        button {display:block}
    </style>
    <script type="text/javascript">
        function test() {
            var button = document.getElementsByTagName("button")[0],
                style = window.getComputedStyle(button),
                coordinates = button.getBoundingClientRect();

            alert (
                "top = " + coordinates.top +
                "\nleft = " + coordinates.left + 
                "\nwidth = " + style.width + //63px
                "\nheight = " + style.height //24px
            );
        }
    </script>
</head>
<body>
    <button id="buttonTest" onClick="test()" >Test it!</button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)