我需要隐藏一个打开网页的 div(显示设置为“无”),但是单击一个按钮必须显示该 div。 在我向每个 div 声明 css 样式之前,我想知道代码为何有效:如果我将样式 block 中的 css 定义到头部(在下面评论)并从每个 div 中删除样式标签,JavaScript 看起来几乎死了。
<!DOCTYPE html>
<HTML lang="it">
<HEAD>
<TITLE>Prova visualizzazione div via button</TITLE>
<meta charset="UTF-8" />
<script>
function apriMenu() {
var idTag;
idTag = document.getElementById("appari").style;
if (idTag.display == "none") {
idTag.display = "block";
idTag.top = document.getElementById("header").style.height + "px";
} else if (idTag.display == "block") {
idTag.display = "none";
}
}
</script>
<!-- <style type="text/css">
header {
width: 100%;
background-color: #22ffff;
height: 40px;
}
#appari {
width: 49%;
background-color: #ff22ff;
height: auto;
display: none;
}
</style> -->
</HEAD>
<body>
<header id="header" style="width: 100%;
background-color: #22ffff;
height: 40px;">
Questo è l'header<br />
<div id="side">
<button onClick="javascript:apriMenu();">Clicca</button>
</div>
</header>
<div id="appari" style="width: 49%;
background-color: #ff22ff;
height: auto;
display: none;">
Questo è il div appari
</div>
</body>
</html>
最佳答案
element.style
只获取内联样式,你要找的是 computedStyle
所以你需要使用 window.getComputedStyle()
查看代码示例:
function apriMenu() {
var idTag;
idTag = document.getElementById("appari");
var displayStyle = window.getComputedStyle(idTag).display;
if (displayStyle === "none") {
idTag.style.display = "block";
idTag.top = document.getElementById("header").style.height + "px";
} else if (displayStyle === "block") {
idTag.style.display = "none";
}
}
header {
width: 100%;
background-color: #22ffff;
height: 40px;
}
#appari {
width: 49%;
background-color: #ff22ff;
height: auto;
display: none;
}
<header id="header">
Questo è l'header<br />
<div id="side">
<button onClick="javascript:apriMenu();">Clicca</button>
</div>
</header>
<div id="appari">
Questo è il div appari
</div>
关于javascript - 通过按钮和 JavaScript 显示或隐藏一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50993080/