js实现广告轮播的实现
广告轮播的实现方法
广告轮播(Carousel)是网页中常见的动态展示效果,通常用于轮流展示多个广告或图片。以下是使用JavaScript实现广告轮播的几种方法。
使用纯JavaScript实现
通过定时器和DOM操作实现轮播效果。
// 获取轮播容器和图片列表
const carousel = document.querySelector('.carousel');
const images = car.querySelectorAll('img');
let currentIndex = 0;
// 切换图片函数
function showImage(index) {
images.forEach((img, i) => {
img.style.display = i === index ? 'block' : 'none';
});
}
// 自动轮播
function startCarousel() {
setInterval(() => {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
}, 3000);
}
// 初始化
showImage(currentIndex);
startCarousel();
使用CSS动画结合JavaScript
通过CSS的@keyframes实现动画效果,JavaScript控制状态。
.carousel {
position: relative;
overflow: hidden;
}
.carousel img {
position: absolute;
width: 100%;
transition: opacity 1s ease-in-out;
opacity: 0;
}
.carousel img.active {
opacity: 1;
}
const images = document.querySelectorAll('.carousel img');
let currentIndex = 0;
function nextImage() {
images[currentIndex].classList.remove('active');
currentIndex = (currentIndex + 1) % images.length;
images[currentIndex].classList.add('active');
}
setInterval(nextImage, 3000);
使用第三方库(如Swiper)
Swiper是一个流行的轮播库,支持丰富的配置和响应式设计。
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide"><img src="image1.jpg"></div>
<div class="swiper-slide"><img src="image2.jpg"></div>
</div>
<div class="swiper-pagination"></div>
</div>
<script>
const swiper = new Swiper('.swiper-container', {
loop: true,
autoplay: {
delay: 3000,
},
pagination: {
el: '.swiper-pagination',
},
});
</script>
实现无限循环轮播
通过动态调整DOM元素实现无缝轮播。
const carousel = document.querySelector('.carousel');
const images = carousel.querySelectorAll('img');
let currentIndex = 0;
function moveToNext() {
currentIndex = (currentIndex + 1) % images.length;
carousel.style.transform = `translateX(-${currentIndex * 100}%)`;
}
setInterval(moveToNext, 3000);
添加导航按钮
为轮播添加手动控制按钮。

const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
prevBtn.addEventListener('click', () => {
currentIndex = (currentIndex - 1 + images.length) % images.length;
showImage(currentIndex);
});
nextBtn.addEventListener('click', () => {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
});
以上方法可以根据需求选择或组合使用,实现灵活多样的广告轮播效果。






