5k.hk 网站背景图片5秒自动更换特效
<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>顺序播放背景图</title> <style> body { margin: 0; padding: 0; overflow-x: hidden; /* 设置页面的外边距为 0,内边距为 0,隐藏水平方向的溢出内容 */ } </style></head>
<body> <!-- 页面内容 -->
<script> // 定义图片数组,包含 8 个不同的图片路径 const images = [ 'https://assets.da8m.cn/79bec02168e25f16a97200f3695063fa6127a59e.jpg', 'https://5k.hk/plugin/zaesky_theme_light/view/img/bgimg/bg-9.png', 'https://assets.da8m.cn/739fa6d08c5155df54f28134b3d462cbd4f01d14.jpg', 'https://assets.da8m.cn/0e516a9ffe4545105aa543a26d5b32a01e93eaea.jpg', 'https://5k.hk/plugin/zaesky_theme_light/view/img/bgimg/bg-7.png', 'https://5k.hk/plugin/zaesky_theme_light/view/img/bgimg/bg-1.png', 'https://5k.hk/plugin/zaesky_theme_light/view/img/bgimg/bg-2.png', 'https://assets.da8m.cn/02415a12b71d68724b0ff56b86e10abcf443da63.jpg' ];
let currentIndex = 0; // 定义一个变量 currentIndex,用于跟踪当前要显示的图片在数组中的索引位置
function setBackgroundImage() { // 定义一个函数 setBackgroundImage,用于设置页面的背景图片 document.body.style.backgroundImage = `url('${images[currentIndex]}')`; // 设置页面 body 的背景图片为当前索引对应的图片路径 document.body.style.backgroundAttachment = 'fixed'; // 设置背景图片固定,不随页面滚动而滚动 document.body.style.backgroundRepeat = 'no-repeat'; // 设置背景图片不重复显示 document.body.style.backgroundSize = 'cover'; // 设置背景图片铺满整个页面
// 递增索引以显示下一张图片,循环播放 currentIndex = (currentIndex + 1) % images.length; // 将 currentIndex 递增,当到达数组末尾时会自动回到开头,实现循环播放 }
// 页面加载时设置一次背景图片 window.onload = setBackgroundImage; // 当页面加载完成时,调用 setBackgroundImage 函数设置初始背景图片
// 每隔一段时间自动更换背景图片 setInterval(setBackgroundImage, 5000); // 使用 setInterval 函数每隔 5000 毫秒(5 秒)自动调用 setBackgroundImage 函数,实现自动切换背景图片的效果 </script></body>
</html>
演示:https://5k.hk/