用js实现图片切换效果
基础图片切换实现
使用HTML和JavaScript创建一个简单的图片切换效果,通过点击按钮切换显示不同的图片。
<!DOCTYPE html>
<html>
<head>
<title>图片切换</title>
</head>
<body>
<img id="image" src="image1.jpg" width="500">
<button onclick="prevImage()">上一张</button>
<button onclick="nextImage()">下一张</button>
<script>
const images = ["image1.jpg", "image2.jpg", "image3.jpg"];
let currentIndex = 0;
function updateImage() {
document.getElementById("image").src = images[currentIndex];
}
function prevImage() {
currentIndex = (currentIndex - 1 + images.length) % images.length;
updateImage();
}
function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
updateImage();
}
</script>
</body>
</html>
自动轮播效果
实现图片自动轮播,每隔一定时间自动切换到下一张图片。
let slideInterval;
function startSlideshow() {
slideInterval = setInterval(nextImage, 2000); // 每2秒切换一次
}
function stopSlideshow() {
clearInterval(slideInterval);
}
// 在页面加载时启动轮播
window.onload = function() {
startSlideshow();
// 鼠标悬停时暂停轮播
document.getElementById("image").addEventListener("mouseover", stopSlideshow);
document.getElementById("image").addEventListener("mouseout", startSlideshow);
};
淡入淡出过渡效果
使用CSS过渡为图片切换添加淡入淡出效果。
<style>
#image {
transition: opacity 0.5s ease-in-out;
}
.fade {
opacity: 0;
}
</style>
<script>
function updateImage() {
const img = document.getElementById("image");
img.classList.add("fade");
setTimeout(() => {
img.src = images[currentIndex];
img.classList.remove("fade");
}, 500);
}
</script>
响应式图片切换
根据屏幕大小动态调整图片显示尺寸。
function resizeImage() {
const img = document.getElementById("image");
if (window.innerWidth < 768) {
img.width = 300;
} else {
img.width = 500;
}
}
window.addEventListener("resize", resizeImage);
缩略图导航
添加缩略图预览功能,点击缩略图可直接跳转到对应图片。
<div id="thumbnails"></div>
<script>
function createThumbnails() {
const container = document.getElementById("thumbnails");
images.forEach((img, index) => {
const thumb = document.createElement("img");
thumb.src = img;
thumb.width = 100;
thumb.onclick = () => {
currentIndex = index;
updateImage();
};
container.appendChild(thumb);
});
}
window.onload = function() {
createThumbnails();
startSlideshow();
};
</script>
触摸滑动支持
为移动设备添加触摸滑动切换图片的功能。
let touchStartX = 0;
let touchEndX = 0;
const imgElement = document.getElementById("image");
imgElement.addEventListener("touchstart", (e) => {
touchStartX = e.changedTouches[0].screenX;
});
imgElement.addEventListener("touchend", (e) => {
touchEndX = e.changedTouches[0].screenX;
handleSwipe();
});
function handleSwipe() {
if (touchEndX < touchStartX - 50) {
nextImage();
}
if (touchEndX > touchStartX + 50) {
prevImage();
}
}
图片预加载
预加载所有图片以提高切换时的用户体验。

function preloadImages() {
images.forEach(imgSrc => {
const img = new Image();
img.src = imgSrc;
});
}
window.onload = function() {
preloadImages();
createThumbnails();
startSlideshow();
};
以上代码示例展示了不同复杂度的图片切换效果实现方法,可以根据实际需求选择适合的方案或组合多个功能。






