gpt4 book ai didi

javascript - 我的 CSS 值不反射(reflect)我的 JavaScript 中的值

转载 作者:技术小花猫 更新时间:2023-10-29 11:51:57 24 4
gpt4 key购买 nike

我正在尝试从 JavaScript 读取 div (div id="navmenu") 的显示值(display:none;display:block;)。但是当我在同一个 html 文件中设置样式值时,我能够读取,但是当我在链接的 CSS 样式表中设置样式值时,它不会读取(结果只是空白)。

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="styles.css" rel="stylesheet" type="text/css" media="screen" />
</head>

<body>
<div id="navmenu">
<p>This is a box of 250px * 250px</p>
</div><!--navmenu-->
<!------------------------------------------------------------------->
<script>
function display(elem) {
return elem.style.display;
}
alert(display(document.getElementById('navmenu')));
</script>
<!------------------------------------------------------------------->
</body>
</html>

enter image description here和CSS

#navmenu {
display:block;
width:250px;
height:250px;
background-color:#3CC;
}

最佳答案

elem.style.display 属性仅报告直接在 DOM 对象上设置的显示属性。它不报告从样式表继承的样式。

要获取样式值(包括来自样式表的样式值),您可以使用 window.getComputedStyle() .

function display(elem) {
return getComputedStyle(elem, null).getPropertyValue("display");
}

关于javascript - 我的 CSS 值不反射(reflect)我的 JavaScript 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30148873/

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