javascript - 在将类添加到另一个元素时删除类

标签 javascript html

我有一长串图像元素,每个元素都有自己的 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');
}

JS Fiddle demo .

引用文献:

关于javascript - 在将类添加到另一个元素时删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17265492/

相关文章:

javascript - 尝试将json文件直接加载到HTML中并通过javascript读取其内容

html - 如何在 Bootstrap 4 网格顶部制作全高 div(从容器边缘右侧滑出)

html - 文本对齐 : justify; not working with wkhtmltopdf

html - 将我的视频放在同一行

javascript - 可以设置水印文字作为背景吗?

javascript - 在 Javascript 中使用 insidetext 来捕获值

javascript - 使传单 map 移动响应

javascript - 如何在一组图像中创建单个图像翻转效果?

javascript - 使按钮关闭一个 div(使用 Wordpress)

events - 收听所有 html 视频事件