使用Swiper这个轮播插件可以使我们用少少的程式码实践轮播效果,它不只可以用来做照片轮播、Banner轮播,还可以做跑马灯效果。今天我们来做个跑马灯吧!
首先我们在官网这一页找到CDN(你也可以用NPM安装),分别把CSS与Javascript CDN 贴在HTML的<head>
中与`前。
CDN:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.css"/><script src="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.js"></script>
然后这是html的程式码结构,最外层是.swiper
容器,再里面有.swiper-wrapper
包覆每张slide用的,
最里面是投影片.swiper-slide
,里面写一些文字。
<!-- Slider main container --><div class="swiper "> <!-- Additional required wrapper --> <div class="swiper-wrapper"> <!-- Slides --> <div class="swiper-slide">今天天气很好,我想要出去玩。今天天气很好,我想要出去玩。今天天气很好,我想要出去玩。今天天气很好,我想要出去玩。天天气很好,我想要出去玩。今天天气很好,我想要出去玩。</div> <div class="swiper-slide">今天天气很好,我想要出去玩。今天天气很好,我想要出去玩。今天天气很好,我想要出去玩。今天天气很好,我想要出去玩。天天气很好,我想要出去玩。今天天气很好,我想要出去玩。</div> <div class="swiper-slide">今天天气很好,我想要出去玩。今天天气很好,我想要出去玩。今天天气很好,我想要出去玩。今天天气很好,我想要出去玩。天天气很好,我想要出去玩。今天天气很好,我想要出去玩。</div> </div></div>
css 样式 我写这样:
//黑底白字.swiper-slide{ width:auto;//让每个投影片宽度auto,使文字不换行,保持单行 font-size:24px; background-color: #000; color:white;}
javascript 长这样:
//初始化Swiper物件,第一个参数对照你swiper的classconst swiper = new Swiper(".swiper", { slidesPerView: "auto", //一个view的投影片数量,预设为1。如果没写这个,若投影片文字过长就会换行 allowTouchMove: false, //不让使用者触碰移动slide autoplay: { delay: 0, //自动播放不延迟 disableOnInteraction: false //不因使用者触碰而停止自动播放 }, loop: true, //反覆循环 speed: 8000 //投影片之间的过渡持续时间(以毫秒为单位),数字愈大跑愈慢});
写到这里会看到跑马灯开始跑了,但速度忽快忽慢。
这时可以在CSS中加这个就可以都一样快:
.swiper-wrapper { transition-timing-function: linear;//使动画变换的速度一样快 }
最后长这样,这是截图
transition-timing-function
让我想到啤酒的广告下面也会有告诫酒后不开车的跑马灯。
完整程式码在此CodePen。
官方API与参数