使用 JavaScript 向元素添加内容样式

Adding content style to an element using 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: "12";
}

到目前为止我尝试的所有方法都没有更新元素。我试图让 + 标志在点击时变成 -

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

知道如何做到这一点吗?

编辑#1:

https://imgur.com/a/jBDcDqX

编辑:

一种方法是在 CSS 中将内容声明为 var,如下所示:

content:var(--content,"+");

然后像这样定位和更改内容:

div.style.setProperty("--content", "'-'")

另外,回答您在评论中关于将内容切换到其之前的“+”状态的其他问题。只需应用一个 boolean,您可以像这样为每次点击更改它:

var bool = false;

  if (bool === false) {
    div.style.setProperty("--content", "'-'")
    bool = true;
  } else if (bool === true) {
    div.style.setProperty("--content", "'+'")
    bool = false;
  }

通过上面的代码,我们可以根据声明为 bool 的布尔值有效地更改内容字符串。当 true 时我们看到 + 并且当 false 时我们看到 -.

请参阅下面的代码段:

var div = document.querySelector('.toggle-box + label');
var bool = false;

function changer() {
  if (bool === false) {
    div.style.setProperty("--content", "'-'")
    bool = true;
  } else if (bool === true) {
    div.style.setProperty("--content", "'+'")
    bool = false;
  }
}
.toggle-box+label:after {
  background-color: #3b434a;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  border-radius: 2px;
  color: #FFFFFF;
  content: var(--content, "+");
  font-weight: bold;
  height: 12px;
  margin-left: 5px;
  text-align: center;
  padding: 0px 2px;
}
<div class="VINDesc">
  <input class="toggle-box" id="toggle" onclick="changer()">
  <label class="VINDesc-label" for="toggle">foo?</label>
  <p>NEW TEXT.</p>
</div>