如何使用@keyframes为div添加下移200px后再上移的动画?
实现div先下移200px再复位的动画效果
你可以通过在动态创建的样式中添加@keyframes规则,并给目标元素绑定动画属性来实现需求。这里用transform: translateY()实现位移,比修改margin更流畅高效。
修改后的JavaScript代码
var style = document.createElement('style'); style.type = 'text/css'; // 新增@keyframes动画规则 + 保留原有元素样式 style.innerHTML = ` @keyframes moveDownUp { 0% { transform: translateY(0); } 50% { transform: translateY(200px); /* 下移200px */ } 100% { transform: translateY(0); /* 回到初始位置 */ } } .moveUp{ background-color:red; width:40px; height:40px; margin:auto; margin-top:3em; animation: moveDownUp 2s ease; /* 绑定动画:名称、时长、缓动函数 */ } `; document.getElementsByTagName('head')[0].appendChild(style);
对应的HTML(无需修改)
<body> <div class="moveUp"></div> <script src="script.js"></script> </body>
关键说明
@keyframes moveDownUp:定义动画的三个关键帧,0%为初始状态,50%完成下移动作,100%回归原位animation属性:指定动画名称moveDownUp、时长2秒,ease是默认缓动效果(可替换为linear等其他值)- 若需要动画循环播放,给
animation添加infinite参数即可,示例:animation: moveDownUp 2s ease infinite;
内容的提问来源于stack exchange,提问作者Teeee
相关产品推荐
相关产品推荐

