为什么警报窗口在这里不显示按钮的宽度?我浏览了类似的问题,但看起来我的问题太简单了,无法在那里找到答案。
<!DOCTYPE html>
<html>
<body>
<button id="jock" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
alert(document.getElementById("jock").style.width);
}
</script>
</body>
</html>
使用 offsetWidth 而不是样式宽度。这将获得元素的真实宽度值。
<!DOCTYPE html>
<html>
<body>
<button id="jock" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert(document.getElementById("jock").offsetWidth);
}
</script>
</body>
</html>
元素中没有声明样式属性。所以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>