首页 > 解决方案 > jQuery Div 切换器

问题描述

我正在使用这个 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 拨动开关,但我不断为每个输入获得两个拨动开关,它仍然有效,但只是试图制作一个打开和关闭的按钮。

标签: jqueryradio-buttontoggle

解决方案


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

制作一个可以打开和关闭的按钮

您需要一个复选框,以便获得一个 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>


推荐阅读