在JavaScript中实现图片切换并添加渐变效果,可以通过CSS和JavaScript配合来完成。以下是实现这一功能的基础概念、步骤和相关代码示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Switch with Fade</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="image-container">
<img id="main-image" src="image1.jpg" alt="Image 1">
</div>
<button id="switch-button">Switch Image</button>
<script src="script.js"></script>
</body>
</html>
.image-container {
position: relative;
width: 500px;
height: 500px;
overflow: hidden;
}
#main-image {
width: 100%;
height: 100%;
transition: opacity 1s ease-in-out;
}
.fade-out {
opacity: 0;
}
.fade-in {
opacity: 1;
}
const mainImage = document.getElementById('main-image');
const switchButton = document.getElementById('switch-button');
let currentImage = 'image1.jpg';
const images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
switchButton.addEventListener('click', () => {
// Fade out the current image
mainImage.classList.add('fade-out');
// Wait for the fade out transition to complete
mainImage.addEventListener('transitionend', () => {
// Switch the image
currentImage = images[(images.indexOf(currentImage) + 1) % images.length];
mainImage.src = currentImage;
// Fade in the new image
mainImage.classList.remove('fade-out');
mainImage.classList.add('fade-in');
// Remove fade-in class after transition ends to reset for next switch
mainImage.addEventListener('transitionend', () => {
mainImage.classList.remove('fade-in');
}, { once: true });
}, { once: true });
});
fade-out
和fade-in
类来控制图片的透明度变化,实现渐变效果。通过这种方式,你可以实现图片的平滑切换,并添加渐变效果,使网页更加生动和吸引人。
领取专属 10元无门槛券
手把手带您无忧上云