首页 > 解决方案 > 我不知道为什么这个动画有效

问题描述

如果 #box 中不存在“位置:绝对”,为什么动画不起作用?

当“位置:绝对”在#box中删除它时,我尝试了此代码,但它不起作用。

<style>
    #box{
        **position:absolute;**
        width:200px;
        height:200px;
        background-color:red;
        animation:animate 2s none infinite alternate;
    }

    @keyframes animate{
        from{
            left:0;
        }
        50%{
            left:500px;
        }
        to{
            left:500px;
        }

    }
</style>

标签: htmlcss

解决方案


您不应该为左/右/上/下设置动画,最好使用transforms。变换允许元素在视觉上移动,而它们在 DOM 上的空间仍然存在,从而使动画更安全/更流畅。

试试这个

#box {
  width: 200px;
  height: 200px;
  background-color: red;
  animation: animate 2s linear forwards infinite alternate;
}

@keyframes animate {
  0% {
    transform: translateX(0px);
  }
  100% {
    transform: translateX(100px);
  }
}

工作演示jsfiddle


推荐阅读