Skip to main content

轮播图实现

原理:通过控制图片的 z-index 属性进行切换

预览链接:http://js.jirengu.com/zikigoloto/1/watch?js,output

//同jQuery:通过$获取单个选择器
const $ = s => document.querySelector(s)
//同jQuery:通过$$获取所有选择器
const $$ = s => document.querySelectorAll(s)

//事件委托:切换小圆点控制图片
$('.carousel .dots').onclick = function(e){
//console.log(this)//父容器
//console.log(e)//选择器

//只有当点击小圆点时触发,否则直接返回
if(e.target.tagName !== 'SPAN'){return}

//获取小圆点下标(indexOf),默认为-1
let index = Array.from($$('.carousel .dots span')).indexOf(e.target)

setSpan(index)
setA(index)
}

//上一页
$('.carousel .action .pre').onclick = function(){
let index = Array.from($$('.carousel .dots span')).indexOf($('.carousel .dots .active'))

index--
if(index<0){
index = 3
}

setSpan(index)
setA(index)
}

//下一页
$('.carousel .action .next').onclick = function(){

let index = Array.from($$('.carousel .dots span')).indexOf($('.carousel .dots .active'))
index++
if(index>3){
index = 0
}
setSpan(index)
setA(index)
}

//封装设置小圆点
function setSpan(index){
//去除小圆点active样式
$$('.carousel .dots span').forEach(span=>span.classList.remove('active'))

//添加指定小圆点active样式
$$('.carousel .dots span')[index].classList.add('active')
}

//封装设置图片
function setA(index){
//统一(去除)图片z-index层级
$$('.carousel .panels a').forEach(a=>a.style.zIndex=1)
//添加指定图片z-index层级
$$('.carousel .panels a')[index].style.zIndex=10
}


function autoNext() {
let index = Array.from($$('.carousel .dots span')).indexOf($('.carousel .dots .active'))
index++
if(index>3){
index = 0
}
setSpan(index)
setA(index)
}

var timer = null;
function autoPlay () {
timer = setInterval(function () {
autoNext();
},2000);
}
autoPlay();

var container = document.querySelector(".carousel");
container.onmouseenter = function () {
clearInterval(timer);
}
container.onmouseleave = function () {
autoPlay();
}

参考文章:https://www.cnblogs.com/zhuzhenwei918/p/6416880.html https://www.jianshu.com/p/bd1f34e7e953