我希望文本隐藏在开头,单击按钮后显示。如果有人能在我的代码中发现错误,我会非常高兴。
function F1()
{
var x = document.getElementById("step1DIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<!DOCTYPE html>
<html>
<body>
<button onclick="F1()"> <b>Step 1</b> </button>
<div id="step1DIV">
<p> text </p>
</div>
</body>
</html>
您需要给它一个初始样式,将其隐藏在HTML中。
function F1()
{
var x = document.getElementById("step1DIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button onclick="F1()"> <b>Step 1</b> </button>
<div id="step1DIV" style="display: none;">
<p> text </p>
</div>
但是内联样式的设计很差,最好使用带有CSS的类。
function F1()
{
var x = document.getElementById("step1DIV");
x.classList.toggle("hidden");
}
.hidden {
display: none;
}
<button onclick="F1()"> <b>Step 1</b> </button>
<div id="step1DIV" class="hidden">
<p> text </p>
</div>
我刚把它定义为"none",开头是这样的:
<div id="step1DIV" style="display: none">
尝试将步骤1div的display
初始设置为none
。使用内联样式或CSS。
您也可以尝试在页面加载时运行您的函数。
您想要切换HTML标准中定义的hidden
属性。
function F1 () {
document.getElementById("a").toggleAttribute("hidden");
}
<!DOCTYPE html>
<html>
<body>
<button onclick="F1()"> <b>Step 1</b> </button>
<div id=a>
<p> text </p>
</div>
</body>
</html>