文章地址 https://www.cnblogs.com/sandraryan/
原生js實現輪播圖。
打開頁面圖片自動輪播,點擊prev next按鈕切換到上/下一張圖片,點擊1-5切換到對應圖片。
大概長這樣 不用加圖片,div就可以實現

css代碼:
.wrap { /* 展示區域樣式 */ width: 500px;height: 400px; box-shadow: 0 0 10px rgba(0,0,0,.5); display: flex; overflow: hidden; position: relative; } .swipe { width: 2500px; display: flex; position: absolute; left: 0; /* 給圖片變化添加過渡效果,時間不能超過定時器一次的時間,否則會沖突 */ transition: .8s; } /* 被輪播的子元素樣式 */ .box{ width: 500px;height: 400px; background-color: rgb(228, 226, 226); color: #fff; font-size: 200px; } button{ width: 100px;height: 40px; margin: 10px 5px; border-radius: 8px; background-color: rgb(202, 202, 202); font-size: 22px; color: white; }
頁面結構:
<!-- 一些按鈕 --> <button class="prev">prev</button> <button class="next">next</button> <br> <button class="btn">one</button> <button class="btn">two</button> <button class="btn">three</button> <button class="btn">four</button> <button class="btn">five</button> <!-- 展示區域 --> <div class="wrap"> <!-- 被輪播的元素父級 --> <div class="swipe"> <!-- 被輪播的子元素列表 --> <div class="box">box1</div> <div class="box">box2</div> <div class="box">box3</div> <div class="box">box4</div> <div class="box">box5</div> </div> </div>
js代碼:
<script>
// 獲取元素
var prev = document.querySelector(".prev");
var next = document.querySelector(".next");
var btns = document.querySelectorAll(".btn");
var swipe = document.querySelector(".swipe");
// 自動播放
// 封裝函數
// 判斷索引,改變left值的函數
function nextFn(){
index = index == 4 ? 0 : ++index;
// 定位元素left才會生效
swipe.style.left = -index * 500 + "px";
}
// 定時器的函數
function autoPlay(){
autoTinmer = setInterval(function(){
// left初始值為0,每張圖片的left是圖片寬度乘圖片數量
// 只有五張圖片,能移動的left最大的left是四張圖的,index等於4的時候恢復到0,否則index++
nextFn();
},2000);
}
// 頁面一刷新就自動播放;
autoPlay();
// 聲明當前展示的圖片的順序
var index = -1;
var autoTinmer;
// 點擊prev next
next.onclick = function(){
// 先停止自動播放 先展示完下一張
clearInterval(autoTinmer);
// 點擊next立即展示下一張
nextFn();
//繼續自動播放
autoPlay();
}
prev.onclick = function(){
clearInterval(autoTinmer);
// 點擊prev立即展示上一張
index = index == 0 ? 4 : --index;
swipe.style.left = -index * 500 + "px";
autoPlay();
}
// 點擊對應順序按鈕
// 循環遍歷所有1-5的button
for(var j = 0; j < btns.length; j++){
// 每一個btn綁定點擊事件
btns[j].onclick = function(){
// 先停止自動播放的定時器
clearInterval(autoTinmer);
// 獲取當前按鈕在btns中的順序獲取到
// 這里不能用indexOf方法,因為這是一個偽數組,不是一個數組,不能使用數組的方法
// getAttribute獲取為標簽自定義html屬性的值
var i = this.getAttribute("data-i");
// console.log(i);
// 根據這個順序設置swipe的left值
swipe.style.left = - i * 500 + "px";
// 恢復自動播放的定時器
autoPlay();
}
}
</script>
the end (●ˇ∀ˇ●)
