我想从第一个元素中删除类,同时使用 JavaScript 添加其他元素
我有四个带有图像的 div,我想在单击面板时添加一个类 .open
,并在单击另一个 div 时从最后一个 div 中删除此类。
<div class="panel panel1">
image..
</div>
<div class="panel panel2">
image..
</div>
<div class="panel panel3">
image..
</div>
<div class="panel panel4">
image..
</div>
<div class="panel panel5">
image..
</div>
当我们添加开放类列表时,该图像容器增长了 5 倍,因此,我想在单击其他图像容器时删除此类:
.panel.open {
font-size: 40px;
flex: 5;
}
const panel = document.querySelectorAll(".panel");
function toggleOpen() {
this.classList.toggle("open");
}
function toggelActive() {
this.classList.add("open-active");
}
panel.forEach((panel) => panel.addEventListener("click", toggleOpen));
panel.forEach((panel) => panel.addEventListener("transitionend", toggelActive));
I have four div with image and I want to add a class .open
when clicked on the panel and remove this class from last div when clicked on another div.
<div class="panel panel1">
image..
</div>
<div class="panel panel2">
image..
</div>
<div class="panel panel3">
image..
</div>
<div class="panel panel4">
image..
</div>
<div class="panel panel5">
image..
</div>
Qhen we add open class list this image container grows 5 time so, I want to remove this class when click on other image container:
.panel.open {
font-size: 40px;
flex: 5;
}
const panel = document.querySelectorAll(".panel");
function toggleOpen() {
this.classList.toggle("open");
}
function toggelActive() {
this.classList.add("open-active");
}
panel.forEach((panel) => panel.addEventListener("click", toggleOpen));
panel.forEach((panel) => panel.addEventListener("transitionend", toggelActive));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 for 循环遍历所有面板,删除“open”类,然后将其添加到单击的面板中:
You could use a for loop to loop over all panels remove the 'open' class and then add it to the clicked panel:
当您使用 querySelectorAll 时,您将得到的结果将是一个 NodeList,您可以通过索引访问元素并更改它们。
如果你能更详细地描述你想要实现的逻辑,也许我可以更好地帮助你。
请记住,要访问第一个元素,索引为 0
when you use querySelectorAll the result you will get will be a NodeList, you can access the elements via index and change them.
If you give a more detailed description of the logic you want to implement, maybe I can help you better.
Remembering that to access the first element the index is 0
我认为您可以向我们提供更多详细信息,但如果您只想在打开另一个图像时关闭图像,您可以从面板中删除所有“打开”类,例如:
I think you could give us more details, but if you just want to close an image when you open another one, you can just remove all "open" classes from your panels, like: