问题
I am trying to achieve a background transition where, when you click on a tab the background of the current tab slides to the tab that is clicked. Can anyone help?
*,
*:before,
*:after {
box-sizing: border-box;
}
.radio_wrap {}
input {
position: absolute;
opacity: 0;
}
label {
min-width: calc(100% / 4);
position: relative;
float: left;
text-align: center;
text-shadow: none;
padding: 20px;
border: 1px solid #dfe0e4;
color: grey;
font-size: 14px;
position: relative;
transition: background-color .3s ease-in-out;
}
input:checked+label {
background: grey;
color: white;
}
<div class="radio_wrap">
<input type="radio" id="radio1" name="radio1">
<label for="radio1">tab1</label>
<input type="radio" id="radio2" name="radio1">
<label for="radio2">tab2</label>
<input type="radio" id="radio3" name="radio1">
<label for="radio3">tab3</label>
<input type="radio" id="radio4" name="radio1">
<label for="radio4">tab4</label>
</div>
回答1:
Here is an idea with pseudo element and CSS variable:
$('label').click(function() {
$('.radio_wrap').attr('style','--i:'+$(this).data('i'));
})
*,
*:before,
*:after {
box-sizing: border-box;
}
input {
position: absolute;
opacity: 0;
}
.radio_wrap {
position:relative;
overflow:hidden;
z-index:0;
--i:-1;
}
.radio_wrap:before {
content:"";
position:absolute;
z-index:-1;
width: calc(100% / 4);
top:1px;
left:calc( var(--i) * (100% / 4));
height:100%;
background:grey;
transition:.3s ease-in-out;
}
label {
min-width: calc(100% / 4);
position: relative;
z-index:2;
float: left;
text-align: center;
text-shadow: none;
padding: 20px;
border: 1px solid #dfe0e4;
color: grey;
font-size: 14px;
position: relative;
transition: color .3s ease-in-out;
}
input:checked+label {
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio_wrap">
<input type="radio" id="radio1" name="radio1">
<label for="radio1" data-i="0">tab1</label>
<input type="radio" id="radio2" name="radio1">
<label for="radio2" data-i="1">tab2</label>
<input type="radio" id="radio3" name="radio1">
<label for="radio3" data-i="2">tab3</label>
<input type="radio" id="radio4" name="radio1">
<label for="radio4" data-i="3">tab4</label>
</div>
来源:https://stackoverflow.com/questions/49439577/tabs-background-color-slide-transition-to-next-tab