我想在不使用html<input>标记的情况下创建一个功能性CSS复选框,但仍在努力实现它。有人能查一下我哪里出错了吗?

var cbElement = document.getElementsByClassName("checkbox1");

cbElement.addEventListener("click", function() {
  var checkbox = document.getElementsByClassName("check");

  if (checkbox.style.visibility == "hidden") {
    document.getElementByClassName("check").style.visibility = "visible";
  } else if (checkbox.style.visibility == "visible") {
    document.getElementsByClassName("check").style.visibility = "hidden";
  }
});

.checkbox1 {
  border: 1px solid black;
  height: 10px;
  width: 10px;
  display: inline-block;
}

.check {
  visibility: hidden;
  color: black;
}

<span class="checkbox1">
  <i class="check"></i>
</span>

<span class="checkbox1">
  <i class="check"></i>
</span>

最佳答案

这是一个纯JS解决方案-一些指针:
getElementsByClassName返回HTMLElement列表
切换class名称比编辑样式更容易
必须给check元素一个background而不是color元素,才能获得选中的感觉。
请参见下面的演示:

var cbElements = document.getElementsByClassName("checkbox1");

for (var i = 0; i < cbElements.length; ++i) {
  cbElements[i].addEventListener("click", function() {
    this.getElementsByClassName("check")[0].classList.toggle('active');
  });
}

.checkbox1 {
  border: 1px solid black;
  height: 10px;
  width: 10px;
  display: inline-block;
  cursor:pointer;
}
.check {
  visibility: hidden;
  background: black;
  display: block;
  height: 100%;
}
.active {
  visibility: visible;
}

<span class="checkbox1">
    <i class="check">&nbsp;</i>
</span>

<span class="checkbox1">
    <i class="check">&nbsp;</i>
</span>

09-25 16:35