如何更改Flickr主页上的背景图像?



我正在尝试克隆Flickr主页,我希望第一张图片在0.3秒内下降,然后图像每4秒改变1秒过渡,除非箭头左或箭头右被按下,在ArrowLeft的情况下,图像应该有一个动画下降到循环中的前一个图像,在ArrowRight被按下的情况下,图像应该下降到循环中的下一个图像,在这两种情况下,图像应该停留4秒,而不是在更短的时间内过渡,如果页面加载开始的间隔被中断。你可以在Flickr主页上看到我的意思。

下面是该问题的代码摘录。

html文档

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<link rel="stylesheet" href="test.css">
<script src="test.js" defer></script>
</head>
<body>
<div id="background"></div>
<div id='grid'>
<header>header</header>
<main>main</main>
<footer>footer</footer>
</div>
</body>
</html>

css文件


* {
margin: 0;
padding: 0;
}
body {
background-color: rgb(50, 50, 50);
display: grid;
}
#background {
height: 100vh;
width: 100%;
background-image: url(./test_images/meditation.jpg);
background-position: center;
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
animation-duration: .3s;
animation-timing-function: ease-out;
animation-delay: 0s;
animation-iteration-count: 1;
animation-name: slideIn;
transition: background-image 1s;
z-index: 0;
}
@keyframes slideIn {
0% {
transform: translateY(-100%);
}
100% {
transform: translateY(0%);
}
}
#grid {
display: grid;
grid-template-rows: 65px 1fr minmax(65px, auto);
height: 100vh;
width: 100%;
z-index: 1;
}
header {
background-color: rgba(0, 0, 0, .5);
color: white;
}
main {
color: white;
}
footer {
color: white;
background-color: black;
}
#grid, #background {
grid-area: 1 / 1;
}

javascript文件

let i = 0;
const backgroundImages = ['meditation.jpg', 'fish.jpg', 'fern.jpg', 'stars.jpg', 'northernLights.jpg', 'forest.jpg', 'mountains.jpg', 'horse.jpg', 'lion.jpg', 'engineer.jpg', 'computers.jpg'];
function changeImages () {
i++;
if (i == backgroundImages.length) {i = 0}
document.getElementById('background').style.backgroundImage = 'url(./test_images/' + backgroundImages[i] + ')';
}
window.onload = function () {
window.setInterval(changeImages, 4000);
}
document.addEventListener('keydown', (event) => {
if (event.key == "ArrowLeft") {
i--;
} else if (event.key == "ArrowRight") {
i++;
}
if (i == -1) {
i = backgroundImages.length - 1;
} else if (i >= backgroundImages.length) {
i = 0;
}
document.getElementById('background').style.backgroundImage = 'url(./test_images/' + backgroundImages[i] + ')';
document.getElementById('background').animate([
{transform: "translateY(-100%)"},
{transform: 'translateY(0%)'}
], {
duration: 300,
iterations: 1
})
window.setInterval(changeImages, 4000);
}, false)

每次设置新的间隔时,使用clearInterval:

取消旧的间隔
let intervalId;
window.onload = function () {
intervalId = window.setInterval(changeImages, 4000);
}
document.addEventListener('keydown', (event) => {
.....
clearInterval(intervalId);
intervalId = window.setInterval(changeImages, 4000);
}, false)

最新更新