【CSS3】使用纯CSS做一个简易轮播图
以下是一个使用纯CSS创建的简易轮播图的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简易轮播图</title>
<style>
.slider {
position: relative;
width: 300px;
height: 200px;
margin: auto;
overflow: hidden;
}
.slider img {
width: 1200px;
height: auto;
position: absolute;
transition: all ease 1s;
}
.slider img:nth-child(n+2) {
left: 300px;
}
.slider img:nth-child(n+3) {
left: 600px;
}
.slider img:nth-child(n+4) {
left: 900px;
}
</style>
</head>
<body>
<div class="slider">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<img src="image4.jpg" alt="Image 4">
</div>
<script>
let currentIndex = 0;
const images = document.querySelectorAll('.slider img');
const imageCount = images.length;
setInterval(function() {
images[currentIndex].style.left = '-300px';
currentIndex = (currentIndex + 1) % imageCount;
images[currentIndex].style.left = '0px';
}, 3000);
</script>
</body>
</html>
这段代码创建了一个简单的轮播图,通过JavaScript的setInterval
函数每三秒更换一次图片。图片通过CSS的position
和left
属性进行定位切换。这个示例假设有四张图片,每张图片的宽度是300px,并且总宽度为1200px,以适配四张并排展示。
评论已关闭