CSS动画:左右手部图片反向旋转实现问题求助
CSS动画:左右手部图片反向旋转实现问题求助
我现在想实现左手和右手向相反方向旋转的效果,看起来像是在展示下方的内容。但目前只能让两个div朝同一个方向转,达不到预期的反向效果——只有右边的手部旋转是符合预期的,左边的完全不对,有没有大佬能帮忙看看怎么解决?
先贴一下我现在的代码:
HTML代码
<div id="handsleft"> <img src="https://syminadivecom.ipage.com/2024/6-hands-left.png" width="400px"> </div> <div id="handsright"> <img src="https://syminadivecom.ipage.com/2024/6-hands-right.png" width="400px"> </div> <div id="gif" style="margin:auto; clear:both; padding-top:100px;"> <h3>example below:</h3> <img src="https://syminadivecom.ipage.com/2024/6-hands-animate.gif" width="300px"> </div>
CSS代码
#handsleft { float: left; width: 50%; width: 600px; color: white; animation: mymove 8s infinite; } @keyframes mymove { 50% { transform: rotate(90deg); } } #handsright { float: left; width: 50%; width: 600px; color: white; animation: mymove 8s infinite; } @keyframes mymove { 50% { transform: rotate(-90deg); } }
问题分析&解决方案
兄弟,你这里的核心坑是重复定义了同名的@keyframes mymove!CSS里后面的@keyframes规则会直接覆盖前面的,所以现在左右两个元素其实都在执行后面那个旋转-90deg的动画,自然左边的就不对了。
解决起来很简单,给两个动画起不同的名字就行,比如一个叫rotateLeft,另一个叫rotateRight,然后分别对应到左右元素上:
修改后的CSS代码:
#handsleft { float: left; width: 600px; /* 你之前重复写了width,留一个就行 */ color: white; animation: rotateLeft 8s infinite; } @keyframes rotateLeft { 50% { transform: rotate(90deg); } } #handsright { float: left; width: 600px; color: white; animation: rotateRight 8s infinite; } @keyframes rotateRight { 50% { transform: rotate(-90deg); } }
另外给个小建议:可以给动画加上ease-in-out过渡效果,让旋转动作更自然,比如把动画属性改成animation: rotateLeft 8s infinite ease-in-out;。
还有布局上的小优化:你用了float:left,如果父容器宽度不够容易换行,换成flex布局会更稳定:
优化版布局(Flex)
CSS:
.hand-container { display: flex; width: 1200px; margin: 0 auto; } #handsleft { width: 600px; color: white; animation: rotateLeft 8s infinite ease-in-out; } #handsright { width: 600px; color: white; animation: rotateRight 8s infinite ease-in-out; }
HTML(把两个手部div包进容器):
<div class="hand-container"> <div id="handsleft"> <img src="https://syminadivecom.ipage.com/2024/6-hands-left.png" width="400px"> </div> <div id="handsright"> <img src="https://syminadivecom.ipage.com/2024/6-hands-right.png" width="400px"> </div> </div> <div id="gif" style="margin:auto; clear:both; padding-top:100px;"> <h3>example below:</h3> <img src="https://syminadivecom.ipage.com/2024/6-hands-animate.gif" width="300px"> </div>
这样调整后,左右手部就能各自朝相反方向旋转,完美实现你想要的展示效果啦~
备注:内容来源于stack exchange,提问作者user3768159
相关产品推荐
相关产品推荐

