javascript - 如何在 Javascript 中隐藏元素
问题描述
我希望文本在开始时隐藏,在单击按钮后显示。如果有人能在我的代码中发现错误,我会非常高兴。
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>
推荐阅读
- daml - 从 DA.Time 存储和检索微秒
- android - 用于 Android 图像处理的 OpenGL ES vs OpenCL vs RenderScript
- python - 如何为类中的类设置值
- marklogic - 在marklogic中可以使用什么排序规则对所有小写字母进行排序?
- javascript - 如何将未知整数划分为给定数量的(几乎)偶数
- sql - 如何从 SQL Server 中的多个项目列表中获取表中存在的一个项目
- json - 如何使用jq获取JSON中所有指定属性的值?
- facebook - 通过我的网站上的 facebook 应用程序分享帖子不起作用
- c# - 如何使用钻孔数据绘制地面剖面?
- node.js - 通过 botbuilder-js SDK 对 MS Graph 进行 API 调用时出错