JavaScript 图片切换动画效果是一种常见的网页交互设计,它允许用户通过点击按钮或其他交互方式来切换显示不同的图片,并伴随一定的动画效果,以提升用户体验。
以下是一个简单的JavaScript图片切换动画效果的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片切换动画</title>
<style>
#imageContainer {
position: relative;
width: 300px;
height: 200px;
overflow: hidden;
}
#imageContainer img {
position: absolute;
width: 100%;
height: auto;
opacity: 0;
transition: opacity 1s ease-in-out;
}
#imageContainer img.active {
opacity: 1;
}
</style>
</head>
<body>
<div id="imageContainer">
<img src="image1.jpg" alt="Image 1" class="active">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<button onclick="prevImage()">Previous</button>
<button onclick="nextImage()">Next</button>
<script>
const images = document.querySelectorAll('#imageContainer img');
let currentIndex = 0;
function showImage(index) {
images.forEach((img, i) => {
img.classList.remove('active');
});
images[index].classList.add('active');
}
function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
}
function prevImage() {
currentIndex = (currentIndex - 1 + images.length) % images.length;
showImage(currentIndex);
}
</script>
</body>
</html>通过以上方法,可以有效地实现和控制JavaScript图片切换动画效果。