从右到左移动图像 - 动画无法正常工作

时间:2015-12-15 19:45:55

标签: html css

我想从右向左移动图像,图像应该从屏幕的右侧进入并从屏幕的左侧退出,因为我已经编写了这个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>

3 个答案:

答案 0 :(得分: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%;}
}

答案 1 :(得分:2)

试试这个

&#13;
&#13;
body {
  position: relative;
  overflow-x: hidden;
}

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

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

translateX(calc(100vw + 350px));中的

350px width的图片,因此图片将显示在图片的窗口 + width的末尾。因此,您必须更改图片宽度,left: -350px相同。

答案 2 :(得分: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的父容器,因此当框不在框架中时,滚动条将不会显示。此外,您在100px中看到的calc也需要与您的元素具有相同的宽度。这是一个js.fiddle with the code。希望有所帮助。

相关问题