我想在包含两个部分的页面上的类之间切换:
当您单击第一个时,它会切换一个名为 open
的类,并将其从最终拥有它的其他部分中删除。
我已经设法使切换功能正常工作,但其他部分
尚未删除open
类。
所以我开始尝试 .filter
但我无法理解它......
行为: 同一时间只能有一个 div 为红色
document.addEventListener("DOMContentLoaded", function(e) {
const sections = document.getElementsByTagName("section");
Array.from(sections).forEach(function(section) {
section.addEventListener('click', function(el) {
//console.log(sections, el)
//var diff = sections.filter(element => element !== section)
//console.log(diff)
section.classList.toggle("open")
});
});
});
body{
margin: 0;
}
main{
width: 100%;
display: flex;
justify-content: center;
flex-direction: row;
}
section{
transition: all 300ms ease-in-out;
padding-top: 2em;
flex-grow: 2;
flex-basis: 0;
display: flex;
flex-direction: column;
}
section:nth-child(1){
background-color: lightblue;
}
section:nth-child(2){
background: rgb(137, 110, 148);
}
section.open{
background: red;
}
img{
width: 90%;
align-self: center;
}
<main>
<section class="left" id="swup" >
<img src="https://picsum.photos/200/300" alt="">
</section>
<section class="right" id="swup" >
<img src="https://picsum.photos/200/400" alt="">
</section>
</main>
最佳答案
您使用 filter()
的方法是正确的,只是忘记先将 sections
转换为数组。
document.addEventListener("DOMContentLoaded", function(e) {
const sections = document.getElementsByTagName("section");
Array.from(sections).forEach(function(section) {
section.addEventListener('click', function(el) {
//console.log(sections, el)
var diff = Array.from(sections).filter(element => element !== section)
diff.forEach(function(otherEl) {
otherEl.classList.remove("open")
})
section.classList.toggle("open")
});
});
});
body{
margin: 0;
}
main{
width: 100%;
display: flex;
justify-content: center;
flex-direction: row;
}
section{
transition: all 300ms ease-in-out;
padding-top: 2em;
flex-grow: 2;
flex-basis: 0;
display: flex;
flex-direction: column;
}
section:nth-child(1){
background-color: lightblue;
}
section:nth-child(2){
background: rgb(137, 110, 148);
}
section.open{
background: red;
}
img{
width: 90%;
align-self: center;
}
<main>
<section class="left" id="swup" >
<img src="https://picsum.photos/200/300" alt="">
</section>
<section class="right" id="swup" >
<img src="https://picsum.photos/200/400" alt="">
</section>
</main>
关于javascript - 使用过滤器切换类并从其他元素中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73837022/