我制作了一个按钮组,希望当用户选择每个按钮时,前一个或后一个按钮的背景可以移动/滑动到所选按钮处。我使用纯
css
实现了这个效果,并只使用 jquery
来添加或删除 active
类。现在的问题是,当你点击 All
按钮,然后点击 New
按钮时,它正常工作,但如果你点击 Used
,则幻灯片不会在正确位置工作。
为了实现这个效果,我使用了 transition
和 ::before
,需要用纯 css
或最小限度的 jquery
解决这个问题,而不是很多的 javascript
或 jquery
代码。
移动这个背景的逻辑是:
.RadioButton .btn:first-child::before {
right: 0;
transition: .3s all ease;
}
.RadioButton .btn:nth-child(2)::before {
transition: .3s all ease;
}
.RadioButton .btn:last-child::before {
left: 0;
transition: .3s all ease;
}
在 .RadioButton .btn:nth-child(2)::before
中,我无法使用 right:0
或 left:0
,因为如果我使用其中任何一个,在正确位置上都不能产生滑动效果,有什么解决办法吗?
我迄今所尝试的:
$('.RadioButton').each(function(){
$(this).find('.btn').each(function(){
$(this).click(function(){
$(this).parent().find('.btn').removeClass('btn-active');
$(this).addClass('btn-active');
});
});
});
body {
direction: rtl;
}
.RadioButton .btn {
width: 33%;
float: left;
margin: 0;
box-sizing: border-box;
position: relative;
font-size: 11px;
min-height: 30px!important;
line-height: 30px;
border-radius: 5px;
overflow: hidden;
cursor: pointer;
text-align: center;
}
.btn-default {
border: 1px solid gray;
color: gray;
}
.btn-group>.btn:first-child {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.btn-group>.btn:nth-child(2) {
border-radius: 0;
}
.btn-group>.btn:last-child {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.RadioButton .btn::before {
content: "";
height: 100%;
width: 0%;
background: gray;
position: absolute;
top: 0;
transition: .3s all ease;
z-index: -1;
}
.btn-active::before {
width: 100%!important;
}
.RadioButton .btn:nth-child(2)::before {
right: 0;
transition: .3s all ease;
}
.RadioButton .btn:last-child::before {
left: 0;
transition: .3s all ease;
}
.btn-active:first-child::before {
left: 0;
transition: .3s all ease;
}
.btn-active:last-child::before {
left: 0;
transition: .3s all ease;
}
.btn.btn-default.btn-active {
color: white;
}
.btn-group {
clear: both;
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="RadioButton btn-group" id="searchType">
<a class="btn btn-default" data-val="0">Used</a>
<a class="btn btn-default" data-val="1">New</a>
<a class="btn btn-default btn-active" data-val="2">All</a>
</div>