我正在尝试为“事件”CSS 类切换“禁用”,以使某些 SVG 的填充属性在单击时发生变化。
我能够正确更改第一个元素,但是当尝试对第二个和第三个 SVG 进行相同更改时,它会更改第一个 div 中第一个元素的颜色。
HTML
<div>
<svg onclick="toggleColor()" class="home__like disable heart">
<use xlink:href="img/sprite.svg#icon-heart-full"></use>
</svg>
</div>
<div>
<svg onclick="toggleColor()" class="home__like disable heart">
<use xlink:href="img/sprite.svg#icon-heart-full"></use>
</svg>
</div>
<div>
<svg onclick="toggleColor()" class="home__like disable heart">
<use xlink:href="img/sprite.svg#icon-heart-full"></use>
</svg>
</div>
CSS
.disable {
fill: #fff;
}
.active {
fill: $color-primary;
}
JavaScript
function toggleColor() {
const toggleHeart = document.querySelector('.heart');
if(toggleHeart.classList.contains('disable')) {
toggleHeart.classList.remove('disable');
toggleHeart.classList.add('active');
} else {
toggleHeart.classList.remove('active');
toggleHeart.classList.add('disable');
}
}
最佳答案
您正在使用 .querySelector()
它返回文档中与提供的选择器匹配的第一个元素。
要获取多个元素,您需要使用 .querySelectorAll()
这将返回静态 NodeList匹配选择器的元素。此时,您需要遍历 NodeList 并操作类。
但是,由于您正在尝试以事件调用元素为目标,我认为您可以通过对该元素的引用来简化它。
function toggleColor(el, e) {
el.classList.toggle('disable');
el.classList.toggle('active');
}
并将您的 onclick
处理程序更改为 onclick="toggleColor(this,event);"
这是一个简短的片段:
function toggleColor(el, e) {
el.classList.toggle('disable');
el.classList.toggle('active');
}
.disable { color: #ccc }
.active { color: #0095ee; }
<div>
<svg class="disable" onclick="toggleColor(this,event);" viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="currentColor" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>
</div>
<div>
<svg class="disable" onclick="toggleColor(this,event);" viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="currentColor" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>
</div>
<div>
<svg class="disable" onclick="toggleColor(this,event);" viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="currentColor" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>
</div>
关于JavaScript Toggle 不适用于许多具有相同类属性的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64670129/