使用 JavaScript 将内容样式添加到元素

我有以下 HTML 标签:


<div class="VINDesc">

    <input class="toggle-box" id="toggle" onclick="sendVinCustomLink()">

    <label class="VINDesc-label" for="toggle">foo?</label>

    <p>NEW TEXT.</p>

</div

标签css如下:


.toggle-box + label:after {

    background-color: #3b434a;

    -webkit-border-radius: 2px;

    -moz-border-radius: 2px;

    border-radius: 2px;

    color: #FFFFFF;

    content: "+";

    font-weight: bold;

    height: 12px;

    margin-left: 5px;

    text-align: center;

    padding: 0px 2px;

}

我的问题是当我点击它时如何添加这种样式:


.toggle-box:checked + label:after {

    content: "\2212";

}

到目前为止我尝试过的所有操作都没有更新该元素。我正在尝试使+标志变成-点击即可。


我向 sendVinCustomLink() 函数添加了功能,但它似乎没有更新标签的相应css.


知道如何做到这一点吗?


DIEA
浏览 69回答 1
1回答

收到一只叮咚

编辑:一种方法是在 CSS 中将内容声明为 var,如下所示:content:var(--content,"+");然后定位并更改内容,如下所示:div.style.setProperty("--content", "'-'")此外,回答评论中有关将内容切换到之前的“+”状态的其他问题。只需应用一个boolean您可以为每次点击更改的值,如下所示:var bool = false;&nbsp; if (bool === false) {&nbsp; &nbsp; div.style.setProperty("--content", "'-'")&nbsp; &nbsp; bool = true;&nbsp; } else if (bool === true) {&nbsp; &nbsp; div.style.setProperty("--content", "'+'")&nbsp; &nbsp; bool = false;&nbsp; }通过上面的代码,我们可以根据我们声明为 的布尔值有效地更改内容字符串bool。当true我们看到+,当false我们看到-。请参阅下面的片段:var div = document.querySelector('.toggle-box + label');var bool = false;function changer() {&nbsp; if (bool === false) {&nbsp; &nbsp; div.style.setProperty("--content", "'-'")&nbsp; &nbsp; bool = true;&nbsp; } else if (bool === true) {&nbsp; &nbsp; div.style.setProperty("--content", "'+'")&nbsp; &nbsp; bool = false;&nbsp; }}.toggle-box+label:after {&nbsp; background-color: #3b434a;&nbsp; -webkit-border-radius: 2px;&nbsp; -moz-border-radius: 2px;&nbsp; border-radius: 2px;&nbsp; color: #FFFFFF;&nbsp; content: var(--content, "+");&nbsp; font-weight: bold;&nbsp; height: 12px;&nbsp; margin-left: 5px;&nbsp; text-align: center;&nbsp; padding: 0px 2px;}<div class="VINDesc">&nbsp; <input class="toggle-box" id="toggle" onclick="changer()">&nbsp; <label class="VINDesc-label" for="toggle">foo?</label>&nbsp; <p>NEW TEXT.</p></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript