史上最簡單的無縫銜接輪播圖
阿新 • • 發佈:2019-01-02
網上有大量關於使用原生js編寫輪播圖的例子,不得不說,他們的文章很棒,但是我發現一個缺點,就是他們的輪播圖元件太過於完整,添加了很多按鈕功能,程式碼量較大。掩蓋了輪播圖的最基本也是最重要的實現原理,很容易讓新手摸不著頭腦。
這篇文章的目的就是想用最少的程式碼,來講解輪播圖的實現原理,實現最基本的功能。等你學會了輪播圖的實現後,至於之後怎麼豐富輪播圖,就是小菜一碟了
效果
思路
將圖片放入列表中,使用CSS浮動使其排成一行,實現無縫銜接。外層為顯示框,設定overflow屬性使其只能顯示一張圖片。通過左移或右移整個列表達到圖片滑動的效果。利用定時器實現自動輪播。
程式碼
html
程式碼很簡單,一個div
裡面是個列表,每張圖片都是一個列表項。本例為一個3張圖片的輪播圖,但你仔細看列表,會發現卻有5個列表項,這是為什麼呢?這是因為為了實現無縫銜接,防止出現滑動空白而特意設定的,在頭部和尾部分別插入了最後一張圖片和第一張圖片,所以最後有3+2=5個列表項。
<body>
<div id="box">
<ul id="pic_list">
<li class="item"><img class="pic" src="./3.jpg" /></li>
<li class="item"><img class="pic" src="./1.jpg" /></li>
<li class="item"><img class="pic" src="./2.jpg" /></li>
<li class="item"><img class="pic" src="./3.jpg" /></li>
<li class="item"><img class="pic" src="./1.jpg" /></li>
</ul>
</div>
<div class="btn">
<button id="prev">前一張</button>
<button id="next">後一張</button>
</div>
<script src="main.js"></script>
</body>
css
樣式中值得注意的是,外部div
的寬度和高度要和圖片一致,且必須設定其overflow:hidden
屬性,使其始終顯示一張圖片。列表項的float
屬性,使圖片排成一行,而ul
列表的寬度為500%
正好對應於5張圖片。
#pic_list{
list-style: none;
height: 300px;
width: 500%;
padding: 0;
margin: 0;
position: relative;
top:0;
}
.pic{
width: 400px;
height:300px;
padding: 0;
margin: 0;
}
.item{
float: left;
}
#box{
width: 400px;
height: 300px;
overflow: hidden;
margin: 0 auto;
border: 1px solid black;
position: relative;
}
.btn{
margin: 10px auto;
width: 150px;
}
js
const images = document.getElementById('pic_list'); //獲取列表
let index = 1; //當前顯示圖片的索引
let length = document.getElementsByClassName('pic').length -2; //獲取圖片的真實數量,不包括頭尾插入的圖片
var animateTimeId = null, toggleTimeId = null; //兩個用於setInterval方法的Id變數
var distance = 0; //頁面滑動的距離
//初始化時,顯示第一張圖片,將列表左移400px
images.style.left = "-400px";
//核心程式碼 頁面滑動動畫
function animate(direction){
if (! animateTimeId){ //當頁面正在執行動畫時,不能再觸發動畫
const step = direction === 1 ? -10 : 10; //確定向左滑還是向右滑
animateTimeId = setInterval(function(){
distance += Math.abs(step);
images.style.left = (parseInt(images.style.left) + step) + 'px'; //每次增加或減少一定值
if (distance >= 400 ) { //當頁面滑動的距離等於或大於圖片的寬度時
clearInterval(animateTimeId); //停止動畫
animateTimeId = null;
distance = 0;
if (step < 0){ //計算滑動後頁面的索引
index += 1;
}else{
index -= 1;
}
if (index === 0){ //如果已滑到列表頭部
index = length;
images.style.left = length * (-400) + 'px'; //將列表左移
}else if (index === 4){ //如果已滑到列表尾部
index = 1;
images.style.left = '-400px'; //將列表右移
}
}
}, 15);
}
}
function Init(){ //初始化,繫結按鈕事件,並啟動自動輪播
const nextButton = document.getElementById('next');
const prevButton = document.getElementById('prev');
const box = document.getElementById('box');
nextButton.onclick = function(){
animate(1);
};
prevButton.onclick = function(){
animate(2);
};
box.addEventListener('mouseenter', function(){
clearInterval(toggleTimeId);
toggleTimeId = null;
});
box.addEventListener('mouseleave', function(){
toggleTimeId = setInterval(function(){
animate(1);
},2500);
});
toggleTimeId = setInterval(function(){
animate(1);
},2500);
}
Init();