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

Javascript - window.getComputedStyle returns "auto" as element top and left properties

本文关键字:顶部 元素 属性 window getComputedStyle 返回 auto Javascript      更新时间:2023-09-26

在我的网页上,我有一些元素(divs,subdivs,按钮等),其位置是相对于它们所在的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>

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>

元素确实将计算position设置为 static 时,没有任何要计算的 topleft(这是默认值)。 在这种情况下,topleft无关紧要。