兩種輪播圖實現方式


  最近做了一個網站,首頁輪播圖一直沒有達到理想的效果,在網上找了兩個實現方法,一個是用css自己實現,一個是用swiper插件,個人認為swiper做的還比較好用。這里只貼出主要的實現代碼,想要看具體實現代碼及效果可以到對應網址上看:

一、css實現輪播圖

原文網址:https://www.jianshu.com/p/550c11f3b731

實現邏輯:

1)將所有的輪播圖片放在一個容器里面,並排排列;

2)編寫css動畫事件:每隔一定時間向左偏移一定距離,距離為一個輪播圖寬度;到最后一個輪播圖后切換到第一個圖片,實現無限循環

優點:

實現邏輯簡單,可以直接拿來用

缺點:

輪播圖數量固定,如果要增刪,需要修改代碼;不是一個順序的無限循環,到達最后一個輪播圖后,會有一個快速倒退的動畫,效果不是太好

主要實現代碼:

/*//自動播放*/
.slide .slide-auto {
    animation: marginLeft 10.5s infinite;
}
@keyframes marginLeft { 0% { margin-left: 0; } 28.5% { margin-left: 0; } 33.3% { margin-left: -600px; } 62% { margin-left: -600px; } 66.7% { margin-left: -1200px; } 95.2% { margin-left: -1200px; } 100% { margin-left: 0; } }

二、swiper插件實現方式

文檔網址:https://www.swiper.com.cn/usage/index.html

實現方法:

1)下載插件文件:swiper-bundle.min.js和swiper-bundle.min.css,下載地址:https://www.swiper.com.cn/download/index.html#file1,下載文件后解壓,在\swiper-master\package目錄下有這兩個文件;

2)引入插件文件:

<!DOCTYPE html>
<html>
<head>
    ...
    <link rel="stylesheet" href="dist/css/swiper-bundle.min.css">
</head>
<body>
    ...
    <script src="dist/js/swiper-bundle.min.js"></script>
    ...
</body>
</html>

3)編寫輪播html頁面:

<div class="swiper-container">
    <div class="swiper-wrapper">
        <div class="swiper-slide">Slide 1</div>
        <div class="swiper-slide">Slide 2</div>
        <div class="swiper-slide">Slide 3</div>
    </div>
    <!-- 如果需要分頁器 -->
    <div class="swiper-pagination"></div>
    
    <!-- 如果需要導航按鈕 -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
    
    <!-- 如果需要滾動條 -->
    <div class="swiper-scrollbar"></div>
</div>

4)JS編寫代碼啟動輪播圖效果

var mySwiper = new Swiper ('.swiper-container', {
    direction: 'vertical', // 垂直切換選項
    loop: true, // 循環模式選項
    
    // 如果需要分頁器
    pagination: {
      el: '.swiper-pagination',
    },
    
    // 如果需要前進后退按鈕
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
    
    // 如果需要滾動條
    scrollbar: {
      el: '.swiper-scrollbar',
    },
  })

優點:

對輪播圖數量沒有限制,增刪輪播圖不需要修改代碼;

功能可配置,自由增刪輪播功能,api文檔地址:https://www.swiper.com.cn/api/index.html

可以外部控制輪播圖,詳細可見api文檔中的Methods(Swiper方法)

提供import引入方式,可應用在vue和react中。

缺點:

有學習成本,不過不高


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM