我正在尝试使用css动画来动画从一个类到另一个类的更改。基本思路是当用户点击按钮时,滑块从一个边滑动到另一个边。
我的代码到目前为止。 https://jsfiddle.net/b5sqvrpz/
.verticalcontainer
{
width: 100%;
display:flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
#pwrbtn.off:after
{
display:block;
height: 100%;
content: "■";
color: blue;
position: relative;
left: -53%;
-webkit-transition: all 1s linear;
-moz-transition: all 1s linear;
-o-transition: all 1s linear;
transition: all 1s linear;
}
#pwrbtn.on:after
{
display:block;
height: 100%;
content: "■";
color: blue;
position: relative;
right: -53%;
-webkit-transition: all 1s linear;
-moz-transition: all 1s linear;
-o-transition: all 1s linear;
transition: all 1s linear;
}
答案 0 :(得分:1)
你不需要2节课,因为" off" class只能是默认样式。此外,您还希望对这两个州使用converter.afterPropertiesSet()
定位,因为您无法将更改从left
设置为left
。最后,您可以简化CSS,因为如果不改变CSS规则,则不需要重复CSS规则。所以对于" on"声明你只需要定义新的right
位置:
left

$(function() {
$('button').click(function() {
$(this).toggleClass('on');
});
});

.verticalcontainer {
width: 100%;
display:flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
#pwrbtn:after {
display:block;
height: 100%;
content: "■";
color: blue;
position: relative;
left: -53%;
-webkit-transition: all 1s linear;
-moz-transition: all 1s linear;
-o-transition: all 1s linear;
transition: all 1s linear;
}
#pwrbtn.on:after {
left:53%;
}

答案 1 :(得分:1)
您可以使用单个伪元素并转换transform
以获得更好的性能。
document.getElementById('pwrbtn').addEventListener('click',function() {
this.classList.toggle('on');
})
.verticalcontainer {
width: 100%;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
#pwrbtn:after {
display: block;
content: "■";
color: #ccc;
position: relative;
left: 0;
-webkit-transition: all .25s linear;
-moz-transition: all .25s linear;
-o-transition: all .25s linear;
transition: all .25s linear;
transform: translateX(-50%);
}
#pwrbtn.on:after {
color: blue;
transform: translateX(50%);
}
<div class="verticalcontainer">
<p>Off</p>
<button id="pwrbtn" class="on"></button>
<p>On</p>
</div>