項目中難免遇到要輪播要滑動的,自己寫一個又太慢,複用性也是問題,我就教你 5 分鐘 搞定swiper,媽媽再也不用擔心我的輪播圖了,下文代碼直接複制即可運作,注釋裡面寫的清清楚楚(最常用到的);
若是在vue中用的話
npm install swiper --save-dev
在要用到swiper的元件中 import 一下,将js初始化部分寫入 vue mounted 鈎子函數裡即可
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.2/css/swiper.css" target="_blank" rel="external nofollow" >
<style>
*{
margin: 0;
padding: 0;
}
.swiper-container {
width: 600px;
height: 300px;
}
.swiper-slide img{
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">
<a href="www.baidu.com" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >
<img src="https://cdn-cnc.test.17zuoye.net/s17/xue/student/public/images/wechat/newDetail/appointment_success.png"alt="">
</a>
</div>
<div class="swiper-slide">
<a href="www.baidu.com" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >
<img src="http://static.17xueba.com/test/server/image/2018/08/20180827110106378711.png" alt="">
</a>
</div>
<div class="swiper-slide">
<a href="www.baidu.com" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >
<img src="http://oimageb1.youdao.com/image?id=5410126604320844202&product=picugc" alt="">
</a>
</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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.0.2/js/swiper.js"></script>
<script>
var mySwiper = new Swiper ('.swiper-container', {
// 如果需要分頁器
pagination: {
el: '.swiper-pagination',
dynamicBullets: true, //動态分頁器
clickable: true, //分頁器控制滑動
},
// 如果需要前進後退按鈕
/*navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},*/
// 如果需要滾動條
/*scrollbar: {
el: '.swiper-scrollbar',
},*/
effect : 'slide',//位移切換 fade-淡入 cube-立體方塊 coverflow-3D流 flip-3D翻轉
// autoplay: true,//可選選項,自動滑動
autoplay : {
delay:1000 // 滑動塊 slide 停留時間
},
speed : 1000, // 自動滑動速度
//grabCursor : true, // 滑鼠到 slide 上變手掌
direction: 'horizontal', // 水準 vertical //垂直
loop: true, // 循環模式選項
initialSlide :0, //預設初始化顯示slide塊
//autoHeight : true, //高度随 slide 變化
//runCallbacksOnInit : false,//初始化時不觸發slideChange
on:{
slideChangeTransitionEnd:function(){
//console.log('滑動完成觸發回調' + this.realIndex);
},
sliderMove: function(){
//console.log('人為滑動');
},
},
//init: false, //false 禁止初始化,在需要的地方使用 mySwiper.init() 來初始化
})
</script>
</body>
</html>