How to use JavaScript to achieve the up and down sliding switching effect of images and add fade-in and fade-out animations?
In web development, it is often necessary to achieve image switching effects. You can use JavaScript to achieve up and down sliding switching, and add fade-in and fade-out animation effects. Let’s take a closer look.
First of all, we need a container that contains multiple images. We can use div tags in HTML to host images. For example, we create a div with the id "image-container" to hold the image.
<div id="image-container"> <img src="image1.jpg"> <img src="image2.jpg"> <img src="image3.jpg"> </div>
Next, we need to write JavaScript code to achieve the switching effect. Here we use event listeners to monitor mouse scroll events and switch images based on the scroll direction.
var container = document.getElementById("image-container"); var images = container.getElementsByTagName("img"); var currentIndex = 0; var imageHeight = images[currentIndex].height; window.addEventListener("wheel", function(event){ var deltaY = event.deltaY; // 滚轮向下滚动,切换至下一张图片 if (deltaY > 0 && currentIndex < images.length - 1) { currentIndex++; } // 滚轮向上滚动,切换至上一张图片 else if (deltaY < 0 && currentIndex > 0) { currentIndex--; } // 计算图片容器需要滚动的距离 var scrollDistance = currentIndex * imageHeight; // 使用CSS的tranform属性实现滑动效果 container.style.transform = "translateY(-" + scrollDistance + "px)"; // 使用CSS的transition属性实现淡入淡出效果 container.style.opacity = 0.5; });
In the above code, deltaY
represents the distance of the scroll wheel, currentIndex
represents the currently displayed image index, imageHeight
represents the height of each image high. By listening to the wheel event, the switching effect is achieved according to the rolling direction of the wheel and the currently displayed image index. Then, use the CSS transform attribute to slide the image container up and down to the corresponding position, and use the transition attribute to set the transparency to achieve a fade-in and fade-out animation effect.
In actual use, relevant styles can be adjusted and optimized according to needs.
The above is a code example that uses JavaScript to achieve the up and down sliding switching effect of an image and add a fade-in and fade-out animation. By listening to the mouse scroll event, we can switch pictures according to the scrolling direction of the wheel, and use the transform property of CSS to achieve the sliding effect, and the transition property to achieve the fade-in and fade-out effect, thus making the picture switching smoother and more vivid.
The above is the detailed content of How to use JavaScript to achieve the up and down sliding switching effect of images and add fade-in and fade-out animations?. For more information, please follow other related articles on the PHP Chinese website!