English

Làm slide ảnh đơn giản với Swiper

z3610422851801_d32fc658de56208174deb9d661482778.jpg

Tác giả

Nguyễn Thị Thanh Tuyền

20/11/2022

Chia sẻ

Screen Shot 2022-11-20 at 13.06.18.png

Chào mừng mọi người đã quay lại với serie học gì chia sẻ nấy và mình là Tuyền. Hôm trước, mình có chia sẻ một ít kiến thức về Interceptor Axios mà mình tìm hiểu được. Tiếp tục, chuỗi seri này thì hôm nay mình sẽ chia sẻ về các thư viện và ngôn ngữ mà mình đã học được và dùng nó trong một dự án mà mình được tham gia. 

Như các bạn đã biết việc làm slide ảnh và hoạt động tốt việc dùng HTML, CSS để viết nên thì nó rất là cất công. Nhận thấy điều đó rất tốn thời gian và công sức cho nên đã có rất nhiều thư viện ra đời và  hỗ trợ cho việc này, phải kể đến các thư viện: Owl Carousel, Slider, Slick, Swiper,... Mình từng dùng thư viện Swiper cho một project của  mình và mình nhận thấy rằng nó đem lại hiệu quả rất tốt cho việc tạo slide, cách dùng cũng rất đơn giản, không cần cài đặt nhiều. Để cài đặt và sử dụng nó chúng ta cần:
Swiper slider là một thư viện hỗ trợ chức năng thu phóng hình ảnh, chạy slider trên web khá hay và đơn giản.
Cài đặt:

- Sử dụng NPM:
$ npm install swiper
- Sử dụng CDN:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.css"/>
<script src="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.js"></script>

Cú pháp cơ bản: 
Thêm đoạn mã vào HTML 

<div class="swiper">
  <div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    ...
  </div>
  <!-- Nếu cần thêm phân trang -->
  <div class="swiper-pagination"></div>
  <!-- Nếu chúng ta cần thêm các nút điều hướng -->
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>
   <!-- Nếu chúng ta cần thanh cuộn -->
  <div class="swiper-scrollbar"></div>
</div>

      Swiper CSS styles/Size:

.swiper {
  width: 600px;
  height: 300px;
}

    Cuối cùng, chúng ta cần khởi tạo JS:

// Thêm thư viện Swiper
import Swiper from 'swiper/bundle';
import 'swiper/css/bundle';
const swiper = new Swiper('.swiper', {
  // Các parameters
  direction: 'vertical',
  loop: true,
  // Nếu chúng ta cần phân trang
  pagination: {
    el: '.swiper-pagination',
  },
  // Các nút điều hướng
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
  // Cần thanh cuộn
  scrollbar: {
    el: '.swiper-scrollbar',
  },
});

Các thuộc tính custom của Navigation:
nextEL: String
Chuỗi CSS selector hoặc phần tử HTML sẽ hoạt động như nút “next” sau khi click vào nó

prevEL: String
Chuỗi CSS selector hoặc phần tử HTML sẽ hoạt động như nút “prev” sau khi click vào nó

Các thuộc tính custom của Pagination:
el: String
Chuỗi CSS selector hoặc phần tử HTML có phân trang và các loại phân trang: “bullets, “fraction”, “progressbar” hoặc “custom”.
Chúng ta cũng có thể chỉnh sửa thuộc tính mặc địch của navigation hoặc pagination bằng cách can thiệp trực tiếp vào class chung của chúng hoặc thêm class khác để cấu hình chúng lại. 

 

//HTML
   <!-- Thêm class chung navigation -->
    <div class="swiper-button-prev navigation"></div>
    <div class="swiper-button-next navigation"></div>
    <!-- Thêm class chung pagination -->
    <div class="swiper-pagination pagination"></div>
//CSS
   .navigation {
    padding:0 20px;
    color: white;
  }
  .pagination{
    bottom:24px;
  }
  .swiper-pagination-bullet {
    height:12px;
    width: 12px;
  }
  .swiper-pagination-bullet-active {
    background-color: #0ea5e9;
  

Ngoài ra chúng ta có thể thêm các Parameters tùy chọn tùy theo mục đích mà ta cần sử dụng:

  // Cho slide trượt tự động sau 3s
autoplay: {
  delay: 3000
},
//Mặc định cho 2 slide ảnh trong 1 khung và khoảng cách cho 2 slide là 12px
slidesPerView: 2,
spaceBetween: 12,
// Tạo điểm ngắt ở từng màn hình cho slide
breakpoints: {
  768: { slidesPerView: 3 }, // 768: sẽ có 3 ảnh được hiển thị
  1024: { slidesPerView: 4 } // 1024: sẽ có 4 ảnh được hiển thị
},

Link code demo: 
https://codepen.io/GreencrisMessi/pen/WNywGyV
*Chú ý: đối với việc nhập 1 ảnh mà không muốn hiển thị các nút điều hướng hay phân trang:

const numberOfSlides = document.querySelectorAll('.swiper-slide').length;
const swiper = new Swiper('.swiper', {
  allowSlidePrev: numberOfSlides === 1 ? false : true,
      allowSlideNext: numberOfSlides === 1 ? false : true,
  autoplay: {
        delay: 3000
      },
      slidesPerView: 1,
      spaceBetween: 12,
      centeredSlides: false,
  pagination: {
    el: '.swiper-pagination',
  },
  navigation: {
        nextEl: document.querySelector('.swiper-button-next'),
        prevEl: document.querySelector('.swiper-button-prev')
      },
      on: {
        init: function () {
          const numberOfSlides = this.slides.length;
          if (numberOfSlides &lt;= 1) {
            this.allowSlidePrev = this.allowSlideNext = false;
            this.el.querySelector('.swiper-button-prev').setAttribute('class', 'hidden');
            this.el.querySelector('.swiper-button-next').setAttribute('class', 'hidden');
          } else {
            this.el.querySelector('.swiper-button-prev').removeAttribute('hidden');
            this.el.querySelector('.swiper-button-next').removeAttribute('hidden');
          }
        }
      }
});


Link code demo:
https://codepen.io/GreencrisMessi/pen/GRGyrzj

Phần mở rộng sử dụng thư viện swiper vào trong Modal (Bootstrap) để tạo popup về slide ảnh:
- Link tham khảo modal trong Bootstrap: https://getbootstrap.com/docs/5.2/components/modal/
- Tạo một Modal đơn giản: 

Link CDN:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384 MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<!-- Nút kích hoạt để mở modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
 Demo
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      //Ở phần body chúng ta có thể thêm đoạn code slide để xem ảnh hiển thị
      <div class="modal-body">
      <div class="swiper">
  <div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    ...
  </div>
  <!-- Nếu cần thêm phân trang -->
  <div class="swiper-pagination"></div>
  <!-- Nếu chúng ta cần thêm các nút điều hướng -->
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>
   <!-- Nếu chúng ta cần thanh cuộn -->
  <div class="swiper-scrollbar"></div>
</div>
</div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Chúng ta, có thể thêm slide ở bất cứ đâu trong modal (header, body, footer). Nhưng mình khuyên các bạn nên để vào phần body để dễ quản lý và kiểm soát code của mình tốt hơn.
Tương tự như cách thêm code HTML, CSS, JS chúng ta cũng viết các file để chạy.
Link code demo: 
https://codepen.io/GreencrisMessi/pen/OJEzWmN

Đây là toàn bộ kiến thức mình học và làm được về Swiper trong dự án của mình.
Cảm ơn các bạn đã đọc tới đây!
Hẹn gặp các bạn ở serie chia sẻ tiếp theo nhé!!!
 

 

Chia sẻ

Liên hệ