js轮播图-面向对象版

效果图如下:


HTML部分:

<div id="main">
		<ul class="imgBox">
			<li><img src="../images/0.png"></li>
			<li><img src="../images/1.png"></li>
			<li><img src="../images/2.png"></li>
			<li><img src="../images/3.png"></li>
		</ul>
	</div>

js部分(面向对象版):

const $=(name)=>document.querySelector(name);
		class Lunbo{
			constructor(name){
				this.box=$(name);
				this.imgBox=$(".imgBox");
				this.img=this.imgBox.getElementsByTagName("img");
				this.createBtn();
				this.autoTimer=null;
				this.moveTimer=null;
				this.num=0;
				this.next();
				//使用了箭头函数以避免定时器中的this指向问题,也可提前设置变量保存this值,否则这里setInterval中this指向window
				this.autoTimer=setInterval(()=>{
					this.next();
				},1000);
				this.box.οnmοuseοver=()=>{
					clearInterval(this.autoTimer);
				}
				this.imgBox.οnmοuseοut=()=>{
					this.autoTimer=setInterval(()=>{
						this.next();
					},1000);
				}
				//同上,使用了箭头函数以避免this指向问题
				for(let i=0;i<this.btn.length;i++){
					this.btn[i].οnmοuseοver=()=>{
						this.num=i;
						this.animate(-this.num*this.img[0].offsetWidth);
						this.btnShow();
					}
				}
			}
			createBtn(){
				let btnBox=document.createElement("ul");
				btnBox.className="btnBox";
				for(let i=0;i<this.img.length;i++){
					let btn=document.createElement("li");
					btn.innerHTML=i+1;
					btnBox.appendChild(btn);
				}
				this.box.appendChild(btnBox);
				this.btn=btnBox.getElementsByTagName("li");
			}
			btnShow(){
				for(let i=0;i<this.img.length;i++){
					this.btn[i].className="";
				}
				this.btn[this.num].className="change";
			}
			//图片切换时的过渡动画
			animate(Pianyi){
				clearInterval(this.moveTimer);//这里之所以要清除过渡动画定时器,是防止过渡动画还未完成便迅速切换时所引发的问题
				this.moveTimer=setInterval(()=>{
					let speed=(Pianyi-this.imgBox.offsetLeft)/6;
					speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
					if (this.imgBox.offsetLeft==Pianyi) {
						clearInterval(this.moveTimer);
					}else{
						this.imgBox.style.left=this.imgBox.offsetLeft+speed+"px";
					}
				},20);
			}
			//方向向右进行滚动,同时改变btn的样式
			next(){
				this.num++;
				if (this.num==this.img.length) {
					this.num=0;
				}
				this.animate(-this.num*this.img[0].offsetWidth);
				this.btnShow();
			}
		}
		window.οnlοad=function(){
			let test=new Lunbo("#main");
		}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值