<!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>Document</title> <style> .slider { margin-left: 300px; margin-top: 50px; width: 900px; height: 300px; } .slides img { margin-left: 0px; width: 100%; height: 500px; } </style> </head> <body> <div class="slider"> <div class="slides"> <img style="background-repeat: no-repeat;" src="images/bj9.jpg"> <img src="images/bj10.jpg"> <img src="images/bj11.jpg"> </div> </div> </body> <script> const slider = document.querySelector('.slider'); const slides = slider.querySelector('.slides').children; const slideCount = slides.length; let currentIndex = 0; function showSlide(index) { if (index < 0) { index = slideCount - 1; } else if (index >= slideCount) { index = 0; } for (let i = 0; i < slideCount; i++) { slides[i].style.display = 'none'; } slides[index].style.display = 'block'; currentIndex = index; } showSlide(currentIndex); setInterval(() => { showSlide(currentIndex + 1); }, 3000); </script> </html>使用swiper代替这段代码
时间: 2024-03-23 19:36:15 浏览: 72
可以使用Swiper来实现轮播图功能,需要先引入Swiper的CSS和JS文件,然后按照以下代码进行设置:
```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>Document</title>
<!-- 引入 Swiper 的 CSS 和 JS 文件 -->
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css" />
</head>
<body>
<!-- Swiper 组件 -->
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide"><img src="images/bj9.jpg"></div>
<div class="swiper-slide"><img src="images/bj10.jpg"></div>
<div class="swiper-slide"><img src="images/bj11.jpg"></div>
</div>
<!-- 如果需要分页器 -->
<div class="swiper-pagination"></div>
</div>
</body>
<!-- 引入 Swiper 的 JS 文件 -->
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
<!-- 初始化 Swiper 组件 -->
<script>
var mySwiper = new Swiper('.swiper-container', {
// 自动播放
autoplay: {
delay: 3000,
disableOnInteraction: false,
},
// 分页器
pagination: {
el: '.swiper-pagination',
clickable: true,
},
});
</script>
</html>
```
在代码中,Swiper的相关设置包括自动播放和分页器等,可以根据自己的需求进行修改。
阅读全文