gpt4 book ai didi

javascript - element.style 显示错误信息

转载 作者:可可西里 更新时间:2023-11-01 12:53:36 24 4
gpt4 key购买 nike

有一个简单的html和javascript代码:

<html>
<head>
<style>p { height: 100px;} </style>
<script>
window.onload = function(){
var p = document.getElementsByTagName("p")[0];
alert("actual height is " + p.style.height);
};
</script>
<title>JavaScript Tests</title>
</head>
<body>
<p>
100px height p element
</p>
</body>
</html>

但是当我们运行它时,实际高度等于空字符串。
你能解释一下为什么吗?
谢谢。

最佳答案

style 属性与 CSS 中的实际样式不同:它查找 style 属性,因此:

<p style="height: 100px"></p>
<script>alert(document.getElementsByTagName("p")[0].style.height);</script>

将是“100px”。

要得到它的实际高度,使用getComputedStyle() .

<style> p { height: 100px; }</style>
<p></p>
<script>alert(getComputedStyle(document.getElementsByTagName("p")[0]).getPropertyValue("height"));</script>

关于javascript - element.style 显示错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4384728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com