2015-12-15 99 views
1

我想从右向左移动图像,图像应该从屏幕的右侧进入并从屏幕的左侧退出,为此我写了这个CSS的动画代码,但它不工作,请帮助。从右向左移动图像 - 动画不能正常工作

.css文件

.imageAnimation { 
    position: 100% 0px; 
    -webkit-animation: moveToLeft 10s linear infinite; 
    animation: moveToLeft 10s linear infinite; 
} 

@-webkit-keyframes moveToLeft { 
    from {position: 100% 0px;} 
    to {position: 0% 0px;} 
} 

@keyframes moveToLeft { 
    from {position: 100% 0px;} 
    to {position: 0% 0px;} 
} 

.HTML文件

<!DOCTYPE html> 
<html> 

    <head> 
     <title>Example</title> 
     <link rel="stylesheet" type="text/css" href="animation.css"/> 
    </head> 

    <body> 
     <img class="imageAnimation" style="position:absolute; top:0px; left:100%;" src="enemy.png" width="300" height="100"/> 
    </body> 

</html> 
+0

你有codepen或jsfiddle的例子吗? – FlipFloop

回答

2

你实际上是非常接近......只是用position不正确。改为使用topleft

.imageAnimation { 
    position: absolute; 
    left: 100%; 
    top: 0px; 
    -webkit-animation: moveToLeft 10s linear infinite; 
    animation: moveToLeft 10s linear infinite; 
} 

@-webkit-keyframes moveToLeft { 
    from {left: 100%;} 
    to {left: 0%;} 
} 

@keyframes moveToLeft { 
    from {left: 100%;} 
    to {left: 0%;} 
} 
2

试试这个

body { 
 
    position: relative; 
 
    overflow-x: hidden; 
 
} 
 

 
img { 
 
    position: absolute; 
 
    animation: moveImage 3s linear infinite; 
 
    left: -350px; 
 
} 
 

 
@keyframes moveImage { 
 
    100% { 
 
     transform: translateX(calc(100vw + 350px)); 
 
    } 
 
}
<img src="http://placehold.it/350x150">

350像素的translateX(calc(100vw + 350px));是图像的width因此图像会去窗口 + width图像的结束。所以你必须改变图像的宽度,对于left: -350px也是如此。

1

我的答案使用calc和百分比,因此该框将从屏幕右侧开始,跨过视图端口区域并且位于屏幕左侧。你可以read about calc browser support here。继承人的代码:

.wrap { 
    background: pink; 
    height: 200px; 
    overflow: hidden; 
    position: relative; 
    width: 100%; 
} 
.box { 
    animation-name: moveToLeft; 
    animation-duration: 5s; 
    background-color: red; 
    height:100px; 
    left:calc(0% - 100px); 
    position:absolute; 
    width:100px; 
} 
@keyframes moveToLeft { 
    0% {left:calc(100% + 100px);} 
    100% {left:calc(0% - 100px);} 
} 

<div class="wrap"> 
    <div class="box"></div> 
</div> 

我使用父容器与overflow: hidden所以当盒是从框架的滚动条将不会显示。您在calc中看到的100px也需要与元素的宽度相同。这是一个js.fiddle with the code。希望有所帮助。