CSS3动画定位

13

考虑使用CSS3动画来使一艘船在蓝色区域上移动。但是出现了某些问题,船没有移动。以下是HTML代码:

<div id="wrapper">
  <div id="sea">
    <img src="ship.png" alt="ship" width="128" height="128"/>
  </div>
</div>
为了制作CSS3动画,我使用以下代码:
#wrapper { position:relative;top:50px;width:700px;height:320px;
          margin:0 auto;background:white;border-radius:10px;}
#sea { position:relative;background:#2875DE;width:700px;height:170px;
       border-radius:10px;top:190px; }
#sea img { 
  position:relative;left:480px;top:-20px;
  animation:myship 10s;
  -moz-animation:myship 10s; /* Firefox */
  -webkit-animation:myship 10s; /* Safari and Chrome */
  @keyframes myship {
    from {left: 480px;} 
    to{left:20px;} 
   }
   @-moz-keyframes myship {
     from {left: 480px;} 
     to {left:20px;} 
   }
   @-webkit-keyframes myship {
     from {left: 480px;} 
     to{left:20px;} 
   }
}

船的图像没有移动。非常感谢您的任何帮助。


1
我知道这是一个旧的帖子,但想分享一下...http://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/ - Praveen Puglia
2个回答

12

你必须在 CSS 选择器之外声明你的关键帧,并且对绝对定位的元素进行动画处理。

http://jsfiddle.net/aNvSf/

你修改后的 CSS 看起来像这样:

#wrapper{
    position:relative;
    top:50px;
    width:700px;
    height:320px;
    margin:0 auto;
    background:white;
    border-radius:10px;
}
#sea{
    position:relative;
    background:#2875DE;
    width:700px;
    height:170px;
    border-radius:10px;
    top:190px;
}
#sea img{
    position:absolute;
    left:480px;
    top:-20px;
    animation:myship 10s;
    -moz-animation:myship 10s; /* Firefox */
    -webkit-animation:myship 10s; /* Safari and Chrome */               
}

@keyframes myship{
    from {left: 480px;} 
    to{left:20px;} 
}
@-moz-keyframes myship{
    from {left: 480px;} 
    to{left:20px;} 
}
@-webkit-keyframes myship{
    from {left: 480px;} 
    to{left:20px;} 
}​

3
要使用 lefttopbottomright 实现动画效果,您需要将元素的定位方式更改为绝对定位或浮动定位。因此,请将其位置改为 absolute

另外,在声明关键帧之前,存在未闭合的大括号 }

#sea img { 
    position:absolute;
    /* ... */
}

大括号错误:

    #sea img{
         position:absolute; /* absolute */
         left:480px;top:-20px;
         animation:myship 10s;
        -moz-animation:myship 10s; /* Firefox */
        -webkit-animation:myship 10s; /* Safari and Chrome */
    } 
 /* ^ You have to close the braces here, before declaring the keyframes.

这里有一个可以使用的演示


@George,你是想给容器还是图片添加动画效果? - Starx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接