我有一长串图像元素,每个元素都有自己的 ID。我已经将其设置为当您单击一张图像时,它将切换一个类“foo”。 我想做的是将其设置为当您单击另一个图像时,第一个图像的类“foo”将被删除。 如果可能的话,我想用纯 JavaScript 来完成此操作。谢谢。
这是一个 fiddle :http://jsfiddle.net/q3aRC/
function clicked($id) {
document.getElementById($id).classList.toggle('foo');
}
最佳答案
考虑到您已经在使用 classList
api,我建议:
function clicked($id) {
// get all the elements with the class-name of 'foo':
var others = document.querySelectorAll('.foo');
// if there *are* any elements with that class-name:
if (others.length){
// iterate through that collection, removing the class-name:
for (var i = 0, len = others.length; i < len; i++){
others[i].classList.remove('foo');
}
}
/* add the class-name back (if it already had the class-name
we removed it in the previous section): */
document.getElementById($id).classList.add('foo');
}
引用文献:
关于javascript - 在将类添加到另一个元素时删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17265492/