使用 JavaScript 按 id 隐藏元素
要按 id 隐藏元素,请使用 getElementById()
方法选择元素并将元素的 style.display
属性设置为 none。 将元素的 display 属性设置为 none 会从 DOM 中删除该元素,就好像该元素从未存在于页面上一样。
这是本文中示例的 HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="box">box</div>
<button id="btn">Hide box</button>
<script src="index.js"></script>
</body>
</html>
这是相关的 JavaScript 代码。
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
const box = document.getElementById('box');
// 👇️ removes element from DOM
box.style.display = 'none';
// 👇️ hides element (still takes up space on page)
// box.style.visibility = 'hidden';
});
我们向按钮元素添加了一个事件侦听器,该按钮元素在单击时隐藏了一个 div
。
我们使用 document.getElementById
方法来获取 id 为 box 的元素。
注意
,我们在示例中使用了display
css 属性,但是根据用例,我们可能需要 visibility 属性。
当元素的 display 属性设置为 none 时,该元素将从 DOM 中删除并且对布局没有影响。 文档呈现为好像该元素不存在。
另一方面,当元素的可见性属性设置为隐藏时,它仍然会占用页面空间,但是该元素是不可见的(未绘制)。 它仍然会像往常一样影响页面上的布局。
如果单击示例中的 button
元素,则 div
元素将从 DOM 中删除,并且 button
元素将取而代之。
这是一个使用可见性属性通过其 id 隐藏元素的示例。
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
const box = document.getElementById('box');
// 👇️ hides element (still takes up space on page)
box.style.visibility = 'hidden';
});
单击按钮时,div
变为不可见,但仍占用页面空间。
另一方面,如果元素的 display 属性设置为 none,它就不再占用页面空间,并且通常其他元素会移动并取而代之。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。