用js实现图片切换效果
基础图片切换实现
通过修改<img>标签的src属性实现图片切换效果:
const images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
let currentIndex = 0;
const imgElement = document.getElementById('myImage');
function changeImage() {
currentIndex = (currentIndex + 1) % images.length;
imgElement.src = images[currentIndex];
}
// 每3秒切换一次
setInterval(changeImage, 3000);
添加过渡动画效果
使用CSS过渡实现淡入淡出效果:
#myImage {
transition: opacity 0.5s ease-in-out;
}
.fade-out {
opacity: 0;
}
function fadeImage() {
imgElement.classList.add('fade-out');
setTimeout(() => {
currentIndex = (currentIndex + 1) % images.length;
imgElement.src = images[currentIndex];
imgElement.classList.remove('fade-out');
}, 500);
}
按钮控制切换
添加前进和后退按钮控制:

document.getElementById('prevBtn').addEventListener('click', () => {
currentIndex = (currentIndex - 1 + images.length) % images.length;
imgElement.src = images[currentIndex];
});
document.getElementById('nextBtn').addEventListener('click', () => {
currentIndex = (currentIndex + 1) % images.length;
imgElement.src = images[currentIndex];
});
缩略图导航实现
创建缩略图点击切换功能:
const thumbnailsContainer = document.getElementById('thumbnails');
images.forEach((image, index) => {
const thumb = document.createElement('img');
thumb.src = image;
thumb.className = 'thumbnail';
thumb.addEventListener('click', () => {
currentIndex = index;
imgElement.src = image;
});
thumbnailsContainer.appendChild(thumb);
});
响应式图片切换
根据窗口大小加载不同尺寸图片:

function getResponsiveImage(index) {
const width = window.innerWidth;
if (width < 768) {
return `mobile-${images[index]}`;
} else if (width < 1024) {
return `tablet-${images[index]}`;
}
return images[index];
}
window.addEventListener('resize', () => {
imgElement.src = getResponsiveImage(currentIndex);
});
预加载图片优化
提升切换流畅度:
function preloadImages() {
images.forEach(image => {
const img = new Image();
img.src = image;
});
}
window.addEventListener('DOMContentLoaded', preloadImages);
无限循环轮播
实现无缝循环效果:
function infiniteCarousel() {
const firstClone = imgElement.cloneNode();
const lastClone = imgElement.cloneNode();
// 添加到DOM
container.insertBefore(lastClone, imgElement);
container.appendChild(firstClone);
let counter = 1;
const size = imgElement.clientWidth;
container.style.transform = `translateX(${-size * counter}px)`;
container.addEventListener('transitionend', () => {
if (imgElement[counter] === lastClone.id) {
container.style.transition = 'none';
counter = images.length - 2;
container.style.transform = `translateX(${-size * counter}px)`;
}
// 类似处理开头情况
});
}






