【发布时间】:2020-12-27 05:13:21
【问题描述】:
单击按钮时,我想将所有类的显示更改为 display: hide;并将它们反转
CSS:
<style>
div.inactive {
display: block;
}
</style>
HTML:
<button onclick="hideInactive()">Show/hide</button>
<div class="inactive">DIV 1: inactive</div>
<p class="inactive">DIV 2: inactive</p>
<ul>
<li class="inactive">
List item 1: Inactive
</li>
<li>
List item 2: Active
</li>
</ul>
JS:
<script>
function hideInactive() {
var x = document.getElementsByClassName('.inactive');
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
我已尝试以这种方式选择所有类:
var x = document.querySelectorAll(".inactive");
我已经尝试遍历每个类:
function hideInactive() {
var x = document.querySelectorAll(".inactive");
for (var i = 0; i < x.length; i++) {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
}
【问题讨论】:
-
getElementsByClassName代码不起作用;见What do querySelectorAll and getElementsBy* methods return?。像onclick这样的内联事件处理程序是not recommended。它们是一种obsolete, hard-to-maintain and unintuitive 注册事件的方式。总是useaddEventListener。 -
另外,在调用
getElementsByClassName时,不要将.放在类的开头。这是 CSS 选择器语法的一部分。您可以将其与querySelectorAll一起使用 -
在您的
querySelectorAll方法中,您循环遍历结果,似乎是因为您知道querySelectorAll返回NodeList,但由于某种原因,您根本没有使用循环。你为什么不在循环体中使用i?另一个潜在问题是Button to show/hide div has to be pressed twice。相反,使用classListAPI 切换类;使用迭代方法而不是for循环。 -
谢谢你们...我还有很多东西要学。我会研究你的建议。
-
@suverenia 我强烈建议您阅读“浏览器像素管道”。 developers.google.com/web/fundamentals/performance/rendering .. 你以后会感谢我的。
标签: javascript html css