JavaScript - Getting Value from switch
本问题已经有最佳答案,请猛点这里访问。
我已经用我真正喜欢的CSS制作了一个"切换"UI元素。它用于开/关场景。基本上是一个花哨的复选框。我的开关在HTML中定义如下:
HTML
1 2 3 4 5 6 7 8 9 10 11 | <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'); } }); |
此组件的CSS如下所示:
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | .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 } |
当用户翻转开关时,
感谢您提供的帮助。
看这个:
1 2 3 4 5 | $('[type="checkbox"]').click(function(e) { var isChecked = $(this).is(":checked"); console.log('isChecked: ' + isChecked); $("#switchText").html(isChecked?'Yes checked':'No checked'); }); |
1 2 3 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> <label class="switch"> <input id="mySwitchCheckbox" type="checkbox" /><span id="switchText">Check-me</span></label> |
您可以使用本机的javascript方式
1 | var isChecked = this.checked; |
或jquery
1 | var isChecked = $(this).prop("checked"); |