jQuery Div Toggle Switcher



我正在使用这个jQuery代码,使用单选按钮切换两个不同的div

$(function() {
$("[name=toggler]").click(function(){
$('.toHide').hide();
$("#blk-"+$(this).val()).show('slow');
});

});

HTML

<label><input id="rdb1" type="checkbox" name="toggler" value="1" />First</label>
<label><input id="rdb2" type="checkbox" name="toggler" value="2" />Second</label>

<div id="blk-1" class="toHide" style="display:none">
First div content
</div>
<div id="blk-2" class="toHide" style="display:none">
Second div content
</div>

这工作棒极了,但我试图把它的样式像一个IOS拨动开关,但我一直得到两个拨动开关为每个输入,它仍然有效,但只是试图使一个按钮打开和关闭。

我需要能够隐藏/显示两个不同的div

创建一个开关键

你需要一个single复选框,这样你就可以得到一个single"IOS"切换按钮。这需要对你的js做一些小改动:

var toShow = $(this).is(":checked") ? "blk-2" : "blk-1";
$("#" + toShow).show('slow');

没有改变你的css(从小提琴链接),给:

$("[name=toggler]").click(function() {
$('.toHide').hide();
var toShow = $(this).is(":checked") ? "blk-2" : "blk-1";
$("#" + toShow).show('slow');
});
/* The switch - the box around the slider */
.toggler {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}

/* Hide default HTML checkbox */
.toggler 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%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="toggler"><input id="rdb1" type="checkbox" name="toggler"/><span class="slider round"></span></label>
<div id="blk-1" class="toHide">
money
</div>
<div id="blk-2" class="toHide" style="display:none">
interest
</div>

最新更新