js实现图片切换
使用JavaScript实现图片切换
图片切换可以通过多种方式实现,以下介绍几种常见的方法。
基础DOM操作切换图片
通过修改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];
}
// 定时切换
setInterval(changeImage, 2000);
使用CSS类切换
通过切换包含不同背景图片的CSS类实现:
const imageContainer = document.getElementById('image-container');
const classes = ['bg-image1', 'bg-image2', 'bg-image3'];
let currentClassIndex = 0;
function toggleImage() {
imageContainer.classList.remove(classes[currentClassIndex]);
currentClassIndex = (currentClassIndex + 1) % classes.length;
imageContainer.classList.add(classes[currentClassIndex]);
}
淡入淡出效果
实现平滑过渡效果:

function fadeSwitch() {
const img = document.getElementById('slideshow');
img.style.opacity = 0;
setTimeout(() => {
img.src = images[currentIndex];
currentIndex = (currentIndex + 1) % images.length;
img.style.opacity = 1;
}, 500);
}
setInterval(fadeSwitch, 2500);
响应式图片切换
根据屏幕尺寸切换不同图片:
function responsiveImageSwitch() {
const screenWidth = window.innerWidth;
const img = document.getElementById('responsive-img');
if(screenWidth < 768) {
img.src = 'mobile.jpg';
} else {
img.src = 'desktop.jpg';
}
}
window.addEventListener('resize', responsiveImageSwitch);
使用事件驱动的切换
通过按钮控制图片切换:
const prevBtn = document.getElementById('prev');
const nextBtn = document.getElementById('next');
prevBtn.addEventListener('click', () => {
currentIndex = (currentIndex - 1 + images.length) % images.length;
updateImage();
});
nextBtn.addEventListener('click', () => {
currentIndex = (currentIndex + 1) % images.length;
updateImage();
});
function updateImage() {
document.getElementById('gallery').src = images[currentIndex];
}
以上方法可以根据具体需求组合使用,创建更复杂的图片切换效果。






