Hướng dẫn làm Zoom in/out slider với Swiper js
14th Feb 2022Hôm nay tôi sẽ hướng dẫn bạn cách tạo hiệu ứng phóng to thu nhỏ đơn giản cùng với Swiper js.
![Swiper](/sites/default/files/inline-images/swiper.gif)
Đầu tiên chúng ta cần import
Bao gồm các kiểu trong phần đầu và tập lệnh vào phần cuối của thẻ nội dung.
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css" /> <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
Add required markup.
<div class="container"> <!-- container to center and set slider width --> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide"> <div class="swiper-zoom-container"> <!-- All "zoomable" images should be wrapped with the div with swiper-zoom-container class. --> <img src="http://pngimg.com/uploads/bottle/bottle_PNG2095.png" /> </div> </div> <div class="swiper-slide"> <div class="swiper-zoom-container"> <img src="http://pngimg.com/uploads/bottle/bottle_PNG2093.png" /> </div> </div> <div class="swiper-slide"> <div class="swiper-zoom-container"> <img src="http://pngimg.com/uploads/bottle/bottle_PNG2081.png" /> </div> </div> </div> </div> </div>
Styles
body { margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; } .container { width: 600px; height: 600px; } .swiper-container, .swiper-wrapper, .swiper-slide { width: 100%; height: 100%; } .swiper-slide img { display: block; margin: 0 auto; width: auto; height: 80%; }
And now it's time to add JavaScript.
// Initialize new Swiper instance const swiper = new Swiper(".swiper-container", { // Setting default settings grabCursor: true, centeredSlides: true, loop: true, // Setting minimum and maximum zoom ration zoom: { maxRatio: 1.2, minRation: 1 }, }); // Use built in zoom.in() and zoom.out() function to scale images // When slide starts to change slideChangeTransitionStart event fires and we use it to scale down the image. swiper.on("slideChangeTransitionStart", swiper.zoom.out); // And when transition has finished scale it up. swiper.on("slideChangeTransitionEnd", swiper.zoom.in);
Add new comment