javascript - 如何将一张图片循环移动到另一张图片之上

标签 javascript css html

enter image description here我们需要创建一个屏幕保护程序,其中一个图像是固定的,第二个图像应该连续向右移动,这样当它向右移动时,图像不存在的左侧部分应该再次被图像填充。我们编码如下所示。

<!DOCTYPE html>
<html>
    <head>
        <title>Moving Screen Saver</title>
        <style>
            html, body {
                position: relative;
                height: 100%;
                width: 100%
            }
            #bgimg {
                background-image: url("background/moon_bg.png");
                position: absolute;
                background-repeat: no-repeat;
                background-size: cover;
                width: 100%;
                height: 100%;
            }
            #bdgimg {
                background-image: url("buildings/bdg6.png");
                position: absolute;
                background-color:transparent;
                bottom: 0px;
                left : 0px;
                width: 100%;
                /*height: 836px;*/
                height: 100%;
            }
        </style>
    </head>
    <body>
        <div id="bgimg">
        </div>
        <div id="bdgimg">
        </div>
        <script type="text/javascript">
            var bdg_img = document.getElementById('bdgimg');
            var animate;
            function moveRight()
            {
                bdg_img.style.left = bdg_img.style.left || 0;
                bdg_img.style.left = parseInt(bdg_img.style.left) + 10 + 'px';
                animate = setTimeout(moveRight,40); // call moveRight in 20msec
            }
            moveRight();
        </script>
    </body>
</html>

这是按预期将第二张图片向右移动,但不确定如何填充左侧部分。我们需要创建一种效果,比如图像不断向右移动,但图像也应该出现在左侧。这意味着由于图像移动,左侧不应出现空白区域。谁能帮我解决这个问题。

最佳答案

我会说你真的不需要 JavaScript 和克隆。您可以使用简单的 @keyframe 动画,为 background-position 设置动画,只要您获得连续重复循环的正确值 (48.1vw, 在下面的示例中 - 当然,它可以是任何倍数,即:96.2vw),以匹配您使用的图像的比例。例如:

.animator {
  background-color: #eee;
  background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/car.svg);
  resize: both;
  overflow: hidden;
  animation: move-background 3s linear infinite;
  padding-bottom: 25%;
  width: 100%;
  background-size: contain;
}
body {
  padding: 0;
  margin: 0;
  font-family: sans-serif;
}
@keyframes move-background {
  0% {
    background-position: 0vw, 0%;
  }
  100% {
    background-position: 48.1vw, 0%;
  }
}
<div class="animator"></div>

关于javascript - 如何将一张图片循环移动到另一张图片之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49762108/

相关文章:

javascript - 从非按钮元素触发按钮点击

javascript - 如何创建一个悬停时出现的 div 并位于两个另一个布局之间?

html - 整个网站响应但仍然可以向右滚动

html - 可以在没有绝对位置的情况下将元素放在表中另一个元素的下方吗?

javascript - 触发Firefox中的所有JavaScript事件

javascript - 等待 promise 链有什么问题?

html - 为什么字段集中的文本有时在移动设备上显得更大?

javascript - 通过 CSS 更改 svg 的笔触颜色

javascript - meteor :如何发布依赖于其他集合游标的游标

php - 尝试在 header.php 中使用样式表的绝对路径 - 不起作用