首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CSS开关(复选框)值总是打开/选中

问CSS开关(复选框)值总是打开/选中
EN

Stack Overflow用户
提问于 2019-09-14 19:01:57
回答 2查看 7.7K关注 0票数 4

我刚刚在CSS中将checkbox设计为toggle switch,它工作得很好。但是,输入的值在onchange事件上似乎没有变化,并且总是显示on。

JS代码:

​

代码语言:javascript
复制
/* The switch - the box around the slider */
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* The slider */
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
代码语言:javascript
复制
<html>
  <head>
  </head>
  <body>
    <center>
      <label class="switch">
        <input type="checkbox" onchange="console.log(this.value);">
        <span class="slider round"></span>
      </label>
    </center>
  </body>
</html>

​

它的视觉行为是完美的,但不是内在的。造成这一问题的原因是什么?知道吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-14 19:16:25

工作示例:https://jsfiddle.net/mg7sLa21/

使用选中的属性确定复选框状态,然后根据该状态分配值。

JS

代码语言:javascript
复制
document.getElementById('checkbox1').addEventListener('change', (e) => {
  this.checkboxValue = e.target.checked ? 'on' : 'off';
  console.log(this.checkboxValue)
})

HTML

代码语言:javascript
复制
<html>

  <head>
  </head>

  <body>
    <center>
      <label class="switch">
        <input id="checkbox1" type="checkbox">
        <span class="slider round"></span>
      </label>
    </center>
  </body>

</html>
票数 5
EN

Stack Overflow用户

发布于 2019-09-14 19:36:17

在一行中,它是浏览器特定的。复选框具有选中的属性,通过该属性可以区分是否选中(on/off)/(真/假)。如果要打印其他内容,而不是“ON”,则添加 value =' true ' value=‘true’属性,该属性将打印“始终为真”或“传递值”。

代码语言:javascript
复制
<input type="checkbox" onchange="console.log(this.checked)">
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57938422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档