0

为什么警告窗口不在这里显示按钮的宽度?我查看了类似的问题,但看起来我的问题太简单了,无法在那里找到答案。

<!DOCTYPE html>
<html>
<body>

<button id="jock" onclick="myFunction()">Try it</button>

    <script>
    function myFunction() 
       {
       alert(document.getElementById("jock").style.width);
       }
    </script>

    </body>
    </html>
4

2 回答 2

2

使用 offsetWidth 代替样式宽度。这将获得元素的真实宽度值。

<!DOCTYPE html>
<html>
<body>

  <button id="jock" onclick="myFunction()">Try it</button>

  <script>
    function myFunction() {
      alert(document.getElementById("jock").offsetWidth);
    }
  </script>

</body>
</html>

于 2017-07-16T14:45:41.530 回答
0

元素中没有声明样式属性。所以document.getElementById("jock").style.width可能行不通,

但是getComputedStyle可以用来获取窗口中按钮的宽度。

function myFunction() {
  var elem1 = document.getElementById("jock")
  var style = window.getComputedStyle(elem1, null);
  console.log(style.width)
}
<button id="jock" onclick="myFunction()"> Try it
  </button>

于 2017-07-16T14:48:11.060 回答