有人可以告诉我在选中一个拨动开关时如何将其他拨动开关更改为未选中状态。我可以使用复选框,但是我发现使用Javascript切换开关非常棘手
if (this.checked) {
$(":checkbox[value=switch-intermediate]").removeAttr("checked", null);
$(":checkbox[value=switch-expert]").removeAttr("Checked",null);
}
我上面的代码可用于复选框,但不适用于拨动开关。我确实在网上看到了一些类似的其他示例,它们来自松弛溢出-Uncheck or turn off all checkbox based toggle switches when a new one is turned on? 但是当我遵循它时,它仍然不起作用。谢谢!
[jfiddle](https://jsfiddle.net/jt100/4xjf1ano/3/)
答案 0 :(得分:1)
通过简单的change
事件和.not(this)
$(".switch:not([checked])")
无需检查if(this.checked)
checked/unchecked
,请使用.prop("checked" , true/false)
this
复选框,请使用.not(this)
$(".switch:not([checked])").on('change' , function(){
$(".switch").not(this).prop("checked" , false);
});
.switch-label {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked + .slider {
background-color: #5c13ec;
}
input:focus + .slider {
box-shadow: 0 0 1px #5c13ec;
}
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%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle-two">
<div>Novice</div>
<label class="switch-label">
<input class="switch" id="switch-novice" value="switch-novice" type="checkbox"/>
<span class="slider round"></span>
</label>
</div>
<div class="toggle-three">
<div>Intermediate</div>
<label class="switch-label">
<input class="switch" id="switch-intermediate" value="switch-intermediate" type="checkbox"/>
<span class="slider round"></span>
</label>
</div>
<div class="toggle-four">
<div>Expert</div>
<label class="switch-label">
<input class="switch" id="switch-expert" value="switch-expert" type="checkbox" />
<span class="slider round"></span>
</label>
</div>
$(this).closest('CONTAINER').find('.switch').not(this)........
代替$('.switch').not(this).....
SEE Example HERE 答案 1 :(得分:0)
将输入从复选框更改为单选按钮,并在所有相关按钮上使用相同的“某物”名称为每个单选按钮添加name="something"
。
基本上,每个输入都从此发生变化
<input class="switch" id="switch-novice"
value="switch-novice" type="checkbox" />
对此
<input class="switch" id="switch-novice"
value="switch-novice" type="radio" name="switch-choice" />
我已经更新了您的fiddle