我们需要从右到左完全移动一个div(背景图像和img在div标签内),一旦div完全消失,我们需要再次从右边开始移动div,但div内部有不同的图像。 / p>
一旦div完全消失,我们将div中的图像源更改为新图像。但是在新图像显示在div上之前,旧图像会暂时显示。
以下是源代码。
<!DOCTYPE html>
<html>
<head>
<style>
html, body {
background-image: url("background/moon_bg.png");
background-repeat: no-repeat;
background-size: cover;
position: relative;
height: 100%;
width: 100%;
margin: 0px;
}
#board {
position: absolute;
background-repeat: no-repeat;
z-index: 99999;
}
</style>
</head>
<body>
<div id="board">
<img id="poster" src="//:0">
</div>
<script>
var board = document.getElementById('board');
var poster = document.getElementById('poster');
var poster_images = ['IronMan.png',
'gladiator.png',
'Ghostbusters.png'];
let bd_image_path = 'url(billboard/b.png)';
let posterIndex = 0;
let newPoster = true;
let posterPath = 'posters/' + poster_images[posterIndex];;
function moveLeft()
{
if(newPoster === true) {
if(poster.complete === true) {
poster.style.left = '10px';
poster.style.top = '65px';
poster.style.width = '422px';
poster.style.height = '198px';
poster.style.position = 'absolute';
board.style.width = "441px";
board.style.height = "395px";
board.style.left = (window.innerWidth - 441) + "px";
board.style.top = (window.innerHeight - 415) + "px";
board.style.backgroundImage = bd_image_path;
poster.style.display = 'block';
newPoster = false;
}
else {
console.log('in else');
}
}
else {
board.style.left = board.style.left || 0;
if(parseInt(board.style.left) <= -(parseInt(board.style.width))) {
newPoster = true;
posterIndex ++;
if(posterIndex >= poster_images.length) {
posterIndex = 0;
}
posterPath = 'posters/' + poster_images[posterIndex];
poster.style.display = 'none';
}
else {
board.style.left = parseInt(board.style.left) - 2 + 'px';
poster.style.left = '10px'
poster.style.top = '65px';
poster.style.width = '422px';
poster.style.height = '198px';
poster.style.position = 'absolute';
poster.src = posterPath;
}
}
requestAnimationFrame(moveLeft);
}
moveLeft();
</script>
</body>
</html>
任何人都可以帮我解决这个问题。
答案 0 :(得分:2)
我认为这归结为缓存问题,您可以通过添加标识符来告知浏览器新图像,时间通常是最简单的方法。
poster.src = posterPath + '?' + new Date().getTime();
答案 1 :(得分:1)
您正在重置每个帧的海报属性,除非电路板刚退出屏幕。下面的静态属性被连续调用,这会干扰src加载并显示一帧的先前图像。
poster.style.left = '10px'
poster.style.top = '65px';
poster.style.width = '422px';
poster.style.height = '198px';
poster.style.position = 'absolute';
poster.src = posterPath;
应该将这些属性(或至少是src属性)添加到上面的if语句中,以便仅在首次请求新海报时调用它们。这将解决问题。但是在实际的服务器上,第一次加载每个新图像需要花费一些时间,因为它们没有被预加载。因此,您还应该添加预加载/缓存例程或事件处理程序,以便仅在下一个图像成功加载(onload)后从右侧启动图像。