我有一个关于事件 onclick 的问题。我在研究过程中发现了这段代码。我的问题是:即使在点击之前文本已经出现,是否可以隐藏文本直到我们点击实际按钮。是否有可能让多个 onclick 事件单独工作,也就是说只打开上面的文本?谢谢
<html>
<head>
<title>Show and hide div with JavaScript</title>
<script>
function showhide()
{
var div = document.getElementById("newpost");
if (div.style.display !== "block") {
div.style.display = "block";
}
else {
div.style.display = "none";
}
}
</script>
</head>
<body>
<div id="newpost">
<p>This div will be show and hide on button click</p>
</div>
<button id="button" onclick="showhide()">Click Me</button>
</body>
</html>
最佳答案
快乐编码:)
function showhide() {
var div = document.getElementById("newpost");
div.classList.toggle('hidden');
}
.hidden{
display : none;
}
<html>
<head>
<title>Show and hide div with JavaScript</title>
</head>
<body>
<!--if you want by default hidden then add class .hidden in new post -->
<div id="newpost" class="hidden">
<p>This div will be show and hide on button click</p>
</div>
<button id="button" onclick="showhide()">Click Me</button>
</body>
</html>
关于javascript - 通过单击 div 隐藏和显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47655563/