html部分
<div class="loopbox">
<div id="box" class="box">
<div class="box-item"><img src="img/1.webp"></div>
<div class="box-item"><img src="img/2.webp"></div>
<div class="box-item"><img src="img/3.webp"></div>
<div class="box-item"><img src="img/4.webp"></div>
</div>
<a class="arrow arrow-left" href="javascript:;" onclick="lunbo.goLeft()">左</a>
<a class="arrow arrow-right" href="javascript:;" onclick="lunbo.goRight()">右</a>
</div>
css部分:
.loopbox{
width: 1200px;
height: 460px;
margin: auto;
position: relative;
overflow: hidden;
border: 1px sienna solid;
}
.box{
width: 100%;
height: 100%;
float: left;
position: relative;
transition: all .3s;
}
.box-item{
width: 100%;
/* width: 1200px; */
height: 100%;
float: left;
background: #f1f1f1;
text-align: center;
font-size: 24px;
line-height: 100px;
/* display: none; */
}
.box-item img {
width: 100%;
height: 100%;
/* 图片适应 */
object-fit: cover;
}
js部分:
//构造函数
function inloop() {
//DOM对象
this.loopboxdata=function(id){
this.loopboxdata=document.getElementsByClassName(id)[0];
return this.loopboxdata;
}
this.boxdom=function(id){
this.boxdom=document.getElementById(id);
return this.boxdom;
}
this.boxitemdata=function(id){
this.boxitemdata=document.getElementsByClassName(id);
return this.boxitemdata;
}
//变量
this.boxwidth = 0;
this.boxitemwidth = 1200;
this.goLoop;
this.index=0;
this.direction = "right";
//方法 设置各个盒子宽度
this.inLoop = function () {
//显示区域长度
this.loopboxdata.style.width = this.boxitemwidth + "px";
this.loopboxdata.style.height = 400 + "px";
//循环总长度
this.boxwidth = this.boxitemwidth * this.boxitemdata.length;
this.boxdom.style.width = this.boxwidth + "px";
// 图片长度;
for (let i = 0; i < this.boxitemdata.length; i++) {
this.boxitemdata[i].style.width = this.boxitemwidth + "px";
}
}
//左按钮
this.goLeft=function() {
this.direction = "left";
this.index--;
if (this.index < 0) {
this.index = this.boxitemdata.length - 1;}
this.goIndex(this.index);
// changeBox(index);
// changePage(index);
}
//右按钮
this.goRight=function() {
this.direction = "right";
this.index++;
if (this.index > this.boxitemdata.length - 1) {
this.index = 0;}
this.goIndex(this.index);
// changeBox(index);
// changePage(index);
}
this.goIndex=function(_index) {
this.index = _index;
this.changeBox(_index);
// changePage(_index);
}
//
this.changeBox=function(_index) {
num= _index * this.boxitemwidth * -1;
console.log(num);
this.boxdom.style.left=num+"px";
}
//定时任务
this.goLoopFunction = function () {
goLoop = setInterval(() => {
this.goRight();
}, 2000);
}
}
://定时任务
this.goLoopFunction = function () {
goLoop = setInterval()=>{
this.goRight();
}, 2000);
}其中箭头函数体内的this
对象,就是定义该函数时所在的作用域指向的对象,而不是使用时所在的作用域指向的对象。