我有CSS3动画,将元素x位置从0移动到100%和100%到200%,但是当它从100%移动到200%时它不会从100%移动而是从0%移动到200%。
@keyframes moveZero {
0%{
transform: translate(0%, 0px);
}
100%{
transform: translate(0%, 0px);
}
}
@keyframes moveOne {
0%{
transform: translate(0%, 0px);
}
100%{
transform: translate(100%, 0px);
}
}
@keyframes moveTwo {
0%{
transform: translate(0%, 0px);
}
100%{
transform: translate(200%, 0px);
}
}
答案 0 :(得分:1)
这是一个纯CSS解决方案:
(Markup已从您的案例中简化,以提供更简单的示例)
<强> HTML 强>
<nav>
<input type="radio" name="radios" id="one"/>
<label for="one" class="nav__button">Button One</label>
<input type="radio" name="radios" id="two"/>
<label for="two" class="nav__button">Button Two</label>
<input type="radio" name="radios" id="three"/>
<label for="three" class="nav__button">Button Three</label>
<div class="nav__bottom"></div>
</nav>
<强> CSS 强>
nav {
position: relative;
width: 450px;
display: flex;
justify-content: space-between;
background-color: white;
}
.nav__button {
padding: 20px 0;
width: 150px;
text-align: center;
transition: .3s;
}
.nav__bottom {
position: absolute;
bottom: 0;
width: 150px;
height: 5px;
background-color: rgb(240, 20, 40);
bottom: 0;
transition: .3s;
}
input[type="radio"] { display: none }
input[type="radio"]:checked + label { background-color: pink; }
input[type="radio"]:nth-of-type(1):checked ~ .nav__bottom{
left: 0;
}
input[type="radio"]:nth-of-type(2):checked ~ .nav__bottom{
left: 150px;
}
input[type="radio"]:nth-of-type(3):checked ~ .nav__bottom{
left: 300px;
}
您可以使用标签选择隐藏的无线电元素,并将:checked
伪选择器与~
兄弟选择器结合使用。
否则,有关您在下面发布的解决方案的一些建议:
使用33%
,66%
等,将不会像您需要的那样精确(例如,在剩余66%的情况下,33%的宽度会让您留下1%的差距)。我更喜欢设置数学,让浏览器为像素做好准备:
left: (100 / 3) + '%' // 33.3333...%
我还发现尽可能多地处理CSS中的转换要容易得多。这就是布局的所有逻辑,所以我更喜欢将它与javascript分开。但是,我们经常需要javascript来进行会影响布局的更改。我喜欢通过在Javascript中添加类并让CSS从那里接管来实现这一点。例如:
// JS
$('button').click(function() {
$('.nav__bar').addClass('active');
})
// CSS
.nav__bar {
position: absolute;
bottom: 0;
left: 0;
width: 0px;
height: 5px;
background: red;
transition: .5s;
}
.nav__bar.active {
width: 100%;
}
我在这里使用这种方法制作了一个JSFiddle的分支:https://jsfiddle.net/hp681kbu/
答案 1 :(得分:0)
最后我找到了jQuery的解决方案,用CSS无法跟踪当前值的动画属性,但是Javascript可以跟踪。所以我在代码中做了一些小改动,删除了所有的CSS动画部分,只添加一行transition: 0.5s
.main__nav{
&__ul{
width: 100%;
position: relative;
height: 50px;
}
&__li{
float: left;
width: 33%;
background-color: #004d85;
display:inline-block;
color: #fff;
font: 12px;
height: 44px;
line-height: 44px;
text-align: center;
}
&__button{
color: #fff;
background: #004d85;
border: none;
}
.animator__span{
position: absolute;bottom: 0;left: 0;
width: 33%;
height: 2px;
background-color: #fff;
transition: 0.5s; /* added */
}
}
并将我的javascript更改为
switch (index) {
case 0:
animatedBorder.css({
'left': '0px'
});
break;
case 1:
animatedBorder.css({
'left': '33%'
});
break;
case 2:
animatedBorder.css({
'left': '66%'
});
break;
default:
animatedBorder.css({
'left': '0px'
});
}
让jQuery为x值设置动画。