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