【问题标题】:JavaScript - Getting Value from switch [duplicate]JavaScript - 从开关中获取价值[重复]
【发布时间】:2016-01-26 20:08:18
【问题描述】:

我使用我非常喜欢的 CSS 制作了一个“切换”UI 元素。它旨在用于开/关场景。基本上,一个花哨的复选框。我的开关在 html 中定义如下:

html

<label class="switch"><input id="mySwitchCheckbox" type="checkbox" /><span id="switchText>Off</span></label>
<script type="text/javascript">
  $('.switch > checkbox').on('change', function(e) {
    alert('here');
    var isChecked = // what goes here?
    if (isChecked) {
      alert('turned on');
    } else {
      alert('turned off');
    }
  });
</script>

我的这个组件的 css 如下所示:

css

.switch {
  cursor:pointer;
  display:inline-block; 
  margin:1px 0;
  position:relative;
  vertical-align:middle
}

.switch input {
  filter:alpha(opacity=0);
  opacity:0;
  position:absolute;
}

.switch span {
  background-color:#c9c9c9; 
  border-radius:12px;
  border:1px solid #eee;    
  display:inline-block; 
  position:relative;
  height:24px;  
  width:52px;
  -webkit-transition:background-color .33s;
  transition:background-color .33s
}

.switch span:after {
  background-color:#fff;    
  border:1px solid #ddd;
  border-radius:20%;    
  bottom:1px;
  content:"";
  left:2px; 
  position:absolute;
  top:1px;
  width:24px;
  -webkit-box-shadow:1px 0 3px rgba(0,0,0,.05);
  box-shadow:1px 0 3px rgba(0,0,0,.05);
  -webkit-transition:all .13s ease-out;
  transition:all .13s ease-out
}

.switch input:checked+span:after {
  left:26px;
  border:none;
  -webkit-box-shadow:-2px 0 3px rgba(0,0,0,.1);
  box-shadow:-2px 0 3px rgba(0,0,0,.1)
}

.switch input:checked+span {
  background-color:#eee
}

.switch span{
  border-color:#818A91
}

.switch input:checked+span{
  background-color:#818A91
}

当用户拨动开关时,onchange 事件被触发。这使我可以访问找到的属性 here。但是,我看不出如何确定开关是打开还是关闭。换句话说,我怎么知道复选框是否被选中?我试图保持实现通用而不是引用 ID,因为一个页面将有多个开关。

感谢您提供的任何帮助。

【问题讨论】:

  • var isChecked = this.checked

标签: javascript css


【解决方案1】:

看这个:

 $('[type="checkbox"]').click(function(e) {
   var isChecked = $(this).is(":checked");
   console.log('isChecked: ' + isChecked);
   $("#switchText").html(isChecked?'Yes checked':'No checked');
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="switch">
  <input id="mySwitchCheckbox" type="checkbox" /><span id="switchText">Check-me</span></label>

【讨论】:

    【解决方案2】:

    可以使用原生javascript方式

    var isChecked = this.checked;
    

    或 jQuery .prop

    var isChecked = $(this).prop("checked");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 2020-01-27
      • 1970-01-01
      相关资源
      最近更新 更多