在我的项目中,我有一个 div,默认设置为 display: none;
。当用户单击图像时,我使用 onclick 函数尝试显示图像。但是由于某种原因这个方法不起作用。
这是我的 HTML:
<img onclick="hamburgerFunc()" class="hamburger-btn" width="38px" src="{% static 'hamburgericon.png' %}" alt="Image of hamburger icon">
<div class="box arrow-top"></div>
<script src="{% static 'home.js' %}"></script>
JS:
function hamburgerFunc(objs) {
objs = document.getElementsByClassName("box arrow-top")
objs.style.display = 'inline-block';
}
更新的代码:
.box.arrow-top:after {
content: " ";
position: absolute;
right: 30px;
top: -15px;
border-top: none;
display: none;
border-right: 15px solid transparent;
border-left: 15px solid transparent;
border-bottom: 15px solid white;
}
顶部箭头是我想要在按下图像后显示的 div。有谁知道为什么这段代码不起作用?谢谢。
最佳答案
getElementsByClassName
返回的不是单个元素,而是一个实时 HTMLCollection。您要么需要迭代所有这些,并为每个单独设置 style
。或者,如果您只期望在元素上直接访问它 objs[0].style.display = ...
const objs = document.getElementsByClassName("box arrow-top")
objs[0].style.display = 'inline-block';
或
const objs = document.getElementsByClassName("box arrow-top")
for (const obj of objs) {
obj.style.display = 'inline-block';
}
或者您可以使用 querySelector
或querySelectorAll
const obj = document.querySelector(".box.arrow-top")
obj.style.display = 'inline-block';
或者如果你确实有多个元素:
const objs = document.querySelectorAll(".box.arrow-top")
for (const obj of objs) {
obj.style.display = 'inline-block';
}
更新
:after
创建 pseudo element ,这些元素不是 DOM 的一部分,无法选择。
您想要做的是从 CSS 规则中删除 display: none;
。以及例如将规则更改为 .box.arrow-top.visible:after
.box.arrow-top.visible:after {
content: " ";
position: absolute;
right: 30px;
top: -15px;
border-top: none;
border-right: 15px solid transparent;
border-left: 15px solid transparent;
border-bottom: 15px solid white;
}
然后执行:
obj.style.classList.add("visible");
关于Javascript - 单击功能给出意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59686764/