js实现banner
实现基础Banner轮播
使用原生JavaScript实现基础Banner轮播功能,以下是核心实现方式:
const banner = document.getElementById('banner');
const images = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
let currentIndex = 0;
function showNextImage() {
currentIndex = (currentIndex + 1) % images.length;
banner.style.backgroundImage = `url(${images[currentIndex]})`;
}
setInterval(showNextImage, 3000);
添加过渡动画效果
为轮播添加平滑的过渡效果,提升用户体验:
banner.style.transition = 'background-image 0.5s ease-in-out';
实现导航控制按钮
添加左右箭头和指示点导航控制:
const prevBtn = document.createElement('div');
prevBtn.className = 'prev-btn';
prevBtn.addEventListener('click', () => {
currentIndex = (currentIndex - 1 + images.length) % images.length;
updateBanner();
});
const nextBtn = document.createElement('div');
nextBtn.className = 'next-btn';
nextBtn.addEventListener('click', () => {
currentIndex = (currentIndex + 1) % images.length;
updateBanner();
});
function updateBanner() {
banner.style.backgroundImage = `url(${images[currentIndex]})`;
updateDots();
}
添加指示点导航
创建与图片数量对应的指示点:
const dotsContainer = document.createElement('div');
dotsContainer.className = 'dots-container';
images.forEach((_, index) => {
const dot = document.createElement('span');
dot.className = 'dot';
dot.addEventListener('click', () => {
currentIndex = index;
updateBanner();
});
dotsContainer.appendChild(dot);
});
function updateDots() {
const dots = document.querySelectorAll('.dot');
dots.forEach((dot, index) => {
dot.classList.toggle('active', index === currentIndex);
});
}
响应式设计处理
确保Banner在不同设备上正常显示:
function resizeBanner() {
banner.style.height = `${window.innerWidth * 0.4}px`;
}
window.addEventListener('resize', resizeBanner);
resizeBanner();
自动播放与暂停功能
添加鼠标悬停暂停功能:
let intervalId = setInterval(showNextImage, 3000);
banner.addEventListener('mouseenter', () => {
clearInterval(intervalId);
});
banner.addEventListener('mouseleave', () => {
intervalId = setInterval(showNextImage, 3000);
});
完整CSS示例
配套的基础CSS样式:
#banner {
width: 100%;
background-size: cover;
background-position: center;
position: relative;
}
.prev-btn, .next-btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
user-select: none;
}
.prev-btn { left: 10px; }
.next-btn { right: 10px; }
.dots-container {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
}
.dot {
display: inline-block;
width: 12px;
height: 12px;
margin: 0 4px;
border-radius: 50%;
background-color: rgba(255,255,255,0.5);
cursor: pointer;
}
.dot.active {
background-color: white;
}
以上代码实现了一个完整的响应式Banner轮播组件,包含自动播放、导航控制、过渡动画等核心功能。可以根据实际需求进一步扩展和定制。







