每次我点击图片时都会出现“未捕获的类型错误:无法读取未定义的属性‘toggle’”
2021-08-29
646
我尝试让元素在用户点击图像后出现。我为此使用了 classlist.toggle,但当我点击图像时,控制台中出现错误消息“Uncaught TypeError:无法读取未定义的属性‘toggle’”。当然,它不起作用 🙁
const plusbtn = document.querySelector(".btn-img");
const drop = document.getElementsByClassName("boxes")
plusbtn.addEventListener('click', () => {
drop.classList.toggle("box-drop");
})
.boxes {
border: 1px solid rgba(39, 81, 197, 0.39);
margin-top: 50px;
padding: 15px;
display: none;
flex-direction: row;
justify-content: space-around;
}
.btn-img {
align-self: center;
filter: grayscale(50%);
cursor: pointer;
}
.box-drop {
display: flex;
}
<section>
<h1>RESOURCES</h1>
<div class="resource-boxes">
<div class="box1">
<div class="top">
<img src="../images/plus.png" alt="" class="btn-img">
</div>
<div class="boxes">
<a href="">
<div class="minibox">
<span class="minibox-txt">Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet consectetur, adipisicing elit. Numquam, enim! </span>
</div>
</a>
</div>
</div>
</div>
</section>
2个回答
getElementsByClassName
返回一个 HTMLCollection
。您需要循环该集合中的每个元素才能访问它。
但是
,由于您已经使用了
.querySelector()
,因此您也可以这样做
-
使用
.querySelectorAll()
返回一个 NodeList ,默认情况下它提供.forEach()
方法 -
不要将元素隐藏在样式定义的位置,而是使用可重用的实用程序类,如
.u-none{ display: none;
const EL_btnPlus = document.querySelector(".btn-img");
const ELS_drop = document.querySelectorAll(".boxes");
EL_btnPlus.addEventListener('click', () => {
ELS_drop.forEach(EL => EL.classList.toggle("u-none"));
});
.boxes {
display: flex;
}
/* Utility classes */
.u-none {
display: none;
}
<img class="btn-img" src="https://lh3.googleusercontent.com/a/AATXAJzyljorAsMuzZ3OQ6B7g_2EU0bkA4lk3iH076AR=k-s64" alt="">
<div class="boxes u-none">Box one</div>
<div class="boxes u-none">Box two</div>
Roko C. Buljan
2021-08-29
drop
是元素列表(请参阅
getElementsByClassName
的返回值)。您必须循环遍历它并在每个单独的元素上切换类:
const plusbtn = document.querySelector(".btn-img");
const drop = [...document.getElementsByClassName("boxes")];
plusbtn.addEventListener('click', () => {
drop.forEach(e => e.classList.toggle("box-drop"));
})
.boxes {
border: 1px solid rgba(39, 81, 197, 0.39);
margin-top: 50px;
padding: 15px;
display: none;
flex-direction: row;
justify-content: space-around;
}
.btn-img {
align-self: center;
filter: grayscale(50%);
cursor: pointer;
}
.box-drop {
display: flex;
}
<section>
<h1>RESOURCES</h1>
<div class="resource-boxes">
<div class="box1">
<div class="top">
<img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1" alt="" class="btn-img">
</div>
<div class="boxes">
<a href="">
<div class="minibox">
<span class="minibox-txt">Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet consectetur, adipisicing elit. Numquam, enim! </span>
</div>
</a>
</div>
</div>
</div>
</section>
Spectric
2021-08-29