jsES6实现轮播

/*
1. 补全页面内容
左按钮 span
右按钮 span
放文字的div
ol
li
2. 设置轮播(控制轮播的当前下标indexA)
1. 图片 : display
2. 小圆点: background
3. 文字
3. 添加事件
1. 左按钮 click indexA –
2. 右按钮 click indexA ++
3. 小圆点 mouseenter indexA = index
4. 自动轮播
setInterval
*/
class Slider{
constructor(id){
//实例属性
//轮播的大盒子
this.bigBox = $id(id);
//获取所有的ul中的li
this.ullis = this.bigBox.children[0].children;
//获取大图数量
this.num = this.ullis.length;
//创建并获取所有的ol中的li
this.ollis = this.createEle();
//设置当前轮播图片的下标
this.indexA = 0;
//获取文字信息的div
this.div = $id(‘msg’);
//调用轮播方法
this.slide();
//获取左按钮
this.ltBtn = $id(‘ltBtn’);
//获取右按钮
this.rtBtn = $id(‘rtBtn’);
//调用添加事件的方法
this.addEvent();
//计时器
this.timer = null;
//调用自动轮播
this.autoPlay();
}
//原型方法
//创建页面元素
createEle(){
// 左按钮 span
let leftSpan = $create(‘span’);
leftSpan.innerHTML = ‘<’;
leftSpan.id = ‘ltBtn’;
this.bigBox.appendChild(leftSpan);
// 右按钮 span
let rightSpan = $create(‘span’);
rightSpan.innerHTML = ‘>’;
rightSpan.id = ‘rtBtn’;
this.bigBox.appendChild(rightSpan);
// 放文字的div
let div = $create(‘div’);
div.id = ‘msg’;
this.bigBox.appendChild(div);
// ol
let arr = [];
let ol = $create(‘ol’);
// li
for(let i = 0;i < this.num;i ++){
let li = $create(‘li’);
ol.appendChild(li);
arr.push(li);
}
this.bigBox.appendChild(ol);
return arr;
}
//设置轮播
slide(){
//图片
for(let i = 0;i < this.num;i ++){
this.ullis[i].style.display = ‘none’;
}
this.ullis[this.indexA].style.display = ‘block’;
//圆点
for(let i = 0;i < this.num;i ++){
this.ollis[i].style.backgroundColor = ‘red’;
}
this.ollis[this.indexA].style.backgroundColor = ‘blue’;
//文字
this.div.innerHTML = this.ullis[this.indexA].firstElementChild.firstElementChild.alt;
}
//添加事件
addEvent(){

	//左 点
	this.ltBtn.onclick = ()=>{
		this.indexA --;
		if(this.indexA === -1){
			this.indexA = this.num - 1;
		}
		//调用轮播
		this.slide();
	}
	//右  点
	this.rtBtn.onclick = ()=>{
		this.indexA ++;
		if(this.indexA === this.num){
			this.indexA = 0;
		}
		this.slide();
	}
	//小圆点  移入
	for(let i = 0;i < this.num;i ++){
		
		this.ollis[i].onmouseenter = ()=>{
			this.indexA = i;
			this.slide();
		}
	}
}
//自动轮播
autoPlay(){

	this.timer = setInterval(()=>{
		this.indexA ++;
		if(this.indexA === this.num){
			this.indexA = 0;
		}
		this.slide();
	},3000)
	//给大盒子添加移入事件
	this.bigBox.onmouseenter = ()=>{
		clearInterval(this.timer);
	}
	//给大盒子添加移出事件
	this.bigBox.onmouseleave = ()=>{
		this.autoPlay();
	}
}

}
//工具箱
function $id(id){
return document.getElementById(id);
}
function $create(tagName){
return document.createElement(tagName);
}

猜你喜欢

转载自blog.csdn.net/weixin_45052104/article/details/91431136