使用原生JavaScript制作一個簡答的圖片輪播效果,沒有實現動畫。原理很簡單,只需要使用DOM對象操作節點的添加和刪除即可實現輪播功能,看一下效果圖:
下面開始上代碼:
HTML代碼
<!-- .swiper是輪播的外部容器
.swiper-item是輪播的每個元素,在該標簽中放置圖片
-->
<div id="swiper">
<div class="swiper-item">
<img src="img/01.jpg">
</div>
<div class="swiper-item">
<img src="img/02.jpg">
</div>
<div class="swiper-item">
<img src="img/03.jpg">
</div>
<div class="swiper-item">
<img src="img/04.jpg">
</div>
</div>
<!-- 分頁指示器 -->
<div id="point">
<div class="point-item point-active"></div>
<div class="point-item"></div>
<div class="point-item"></div>
<div class="point-item"></div>
</div>
<!-- 控制輪播的按鈕 -->
<div style="text-align: center;">
<button id="up">上一張</button>
<button id="down">下一張</button>
</div>
CSS代碼:
/* 輪播外部容器樣式 */
#swiper {
margin: 10px auto;
width: 360px;
height: 200px;
border: 1px solid #999;
overflow: hidden; /* 注釋本行代碼,查看圖片的輪播效果 */
}
/* 設置輪播圖片樣式 */
.swiper-item img {
width: 100%;
}
/* 分頁指示器樣式 */
#point {
width: 80px;
height: 15px;
margin: 10px auto;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
}
.point-item {
border: 1px solid #999;
width: 10px;
height: 10px;
border-radius: 50%;
}
/* 指示器激活樣式 */
.point-active {
background-color: red;
}
JavaScript代碼:
//獲取輪播容器對象 和 分頁指示器元素對象
var swiper = document.getElementById('swiper');
var point = document.getElementById('point');
//播放下一張圖片的方法
function changeAfter() {
//1. 刪除輪播容器中第一個子元素,並返回被刪除的元素對象
//swiper.children 返回swiper元素下的所有子元素
var child = swiper.removeChild(swiper.children[0]);
//2. 將被刪除元素追加到輪播容器的末尾
swiper.appendChild(child);
//設置分頁指示器的輪播效果,要與圖片輪播順序相反
var index = point.children.length - 1;
var pointItem = point.removeChild(point.children[index]);
point.insertBefore(pointItem, point.children[0]);
}
//播放上一張圖片的方法
function changeBefore() {
//1. 獲取最后一張在輪播容器中的的下標
var index = swiper.children.length - 1;
//2. 把最后一張刪除,並返回被刪除的元素對象
var child = swiper.removeChild(swiper.children[index]);
//3. 將被刪除元素添加到第一張之前
swiper.insertBefore(child, swiper.children[0]);
//設置分頁指示器的輪播效果,要與圖片輪播順序相反
var pointItem = point.removeChild(point.children[0]);
point.appendChild(pointItem);
}
//上一張按鈕點擊事件
document.getElementById("up").onclick = function() {
changeBefore(); //調用輪播上一張的方法
}
//下一張按鈕點擊事件
document.getElementById("down").onclick = function() {
changeAfter(); //調用輪播下一張的方法
}
//定時輪播
setInterval('changeAfter()', 3000);