JavaScript - 类切换正在删除类,而不是在下一次单击时添加

时间:2018-01-16 17:43:45

标签: javascript html css

我在i标签上设置了一个eventlistener with class = glyphcolor我想要做的是每当我看到类checkglyph1的元素时它必须切换类,即如果类在那里它必须被删除,如果没有添加checkglyph1类的作用是改变文本的颜色。

实际结果

image to the output I get

首次点击时我看到第一个元素默认切换到此处我已经设置了它。在下一次点击时它会被移除而不是切换。

HTML部分:

<div class="row datasection">
    <div class="todo">
        <div class="databox col s6 waves-effect">
            <p class="checkglyph1 ">Task to do</p>
            <!--   </div>  -->
            <a>
                <i class="material-icons checkglyph checkglyph1 glyphcolor">check</i>
            </a>
        </div>
    </div>
</div>           

JS:

var glyph= document.querySelector('.glyphcolor');
var par=  document.getElementsByClassName('checkglyph1');
console.log(par[0]);
console.log(par[1]);
glyph.addEventListener('click', function () {
    /* body... */
    console.log("Qw");
    par[0].classList.toggle("checkglyph1");
    console.log(par[0]);
    par[1].classList.toggle("checkglyph1");

})

CSS:

.datasection .todo .databox {
    background-color: teal;
    margin-left: 120px;
    border-radius: 10px;
    position: relative;
    display: inline-block;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.databox p{
    display: inline-block;
}

.databox a .checkglyph{
    display: inline-block;
    color: yellow;
    position: absolute;
    left: 90%;
    top: 25%;
}

.databox a .checkglyph:hover{
    display: inline-block;
}

.databox a .checkglyph1{
    display: inline-block;
    color: white;
    cursor: pointer;
}

.databox .checkglyph1{
    color: white;
    cursor: text;
}

1 个答案:

答案 0 :(得分:1)

getElementsByClassName是一个LIVE Html Collection。删除该类,该项目将从集合中删除。

&#13;
&#13;
var elems = document.getElementsByClassName("foo")
console.log("before", elems.length);
elems[0].classList.remove("foo");

console.log("after", elems.length);
&#13;
.foo { color: red; }
&#13;
<div class="foo">1</div>
<div class="foo">2</div>
&#13;
&#13;
&#13;