用js实现轮播效果,不管图片尺寸是多少,都能自适应整个页面,下面是一个简单的demo。
HTML框架
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<!-- 整体框架 -->
<div class="carousel">
<!-- 轮播图片 -->
<img src="Images/1.jpg">
<img src="Images/2.jpg">
<img src="Images/3.jpg">
</div>
</body>
</html>
CSS渲染
<style>
body,
html {
height: 100%;
margin: 0;
padding: 0;
}
.carousel {
/* 设置相对定位 */
position: relative;
height: 100%;
width: 100%;
/* 隐藏溢出部分 */
overflow: hidden;
}
.carousel img:first-child{
/* 设置绝对定位 */
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
/* 初始设置图片透明度为1 */
opacity: 1;
/* 设置渐变过渡效果 */
transition: opacity 2s;
}
.carousel img:not(:first-child) {
/* 设置绝对定位 */
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
/* 初始设置图片透明度为0 */
opacity: 0;
/* 设置渐变过渡效果 */
transition: opacity 2s;
}
</style>
JavaScript
<script>
let carousel = document.querySelector('.carousel');
let images = carousel.querySelectorAll('img');
let currentImgIndex = 0;
function showNextImage() {
images[currentImgIndex].style.opacity = 0; // 隐藏当前图片
currentImgIndex = (currentImgIndex + 1) % images.length; // 计算下一张图片的索引
images[currentImgIndex].style.opacity = 1; // 显示下一张图片
}
// 设置定时器,每5秒切换图片
setInterval(showNextImage, 5000);
</script>