JSFiddle - React, Tailwind, and code Playground
HTML
<div id="focusBox" >
<ul id="focus_pic" style="top:0;left:0;">
<li><a target="_blank" href="#"><img src="1.jpg" width="530" height="180"></a></li>
<li><a target="_blank" href="#"><img src="2.jpg" width="530" height="180"></a></li>
<li><a target="_blank" href="#"><img src="3.jpg" width="530" height="180"></a></li>
<li><a target="_blank" href="#"><img src="4.jpg" width="530" height="180"></a></li>
<li><a target="_blank" href="#"><img src="5.jpg" width="530" height="180"></a></li>
</ul>
</div>
CSS
#focusBox{ width:530px; height:180px; position:relative; margin:0 auto; zoom:1; overflow:hidden;}
#focusBox img{border:none; margin:0;padding:0;}
#focusBox ul { list-style:none; padding:0; margin:0; position: absolute;}
#focusBox #focus_pic li{ height:180px; width:530px; margin:0; padding:0; float:left}
#focusBox #focus_btn { right:5px; bottom:5px; z-index:2;}
#focusBox #focus_btn li{ float:left;border-radius:20px; font-size:12px; width:25px; height:25px; line-height:25px; font-weight:bold; text-align:center; background:#fff; color:#000; margin-right:2px; cursor:pointer;}
#focusBox #focus_btn li.active{ background:#f60; color:#fff;}
JavaScript
function focusBox(id,oo){
this.$ = function(id){return document.getElementById(id)};
this.id = id;
this.oo = oo;//oo.v, oo.width, oo.height, oo.btnId, oo.on, oo.autoTime
this.index = 0;
return this.init();
}
focusBox.prototype = {
init : function(){//初始化设置
this.picLis = this.$(this.id).getElementsByTagName("li");//图片lis
this.createBtn(this.oo.btnId);//创建数字按钮
this.btnLis = this.$(this.oo.btnId).getElementsByTagName("li");//按钮lis
this.oo.v==0 ? this.$(this.id).style.width = this.oo.width*this.btnLis.length + "px" : this.$(this.id).style.width = this.oo.width +"px";//判断滚动方向 修改ul的宽度
this.btnHover();
this.autoPlay();
},
autoPlay : function(){//定时器
this.moveIndex(this.index);
for(var i=0; i<this.btnLis.length; i++){
this.btnLis[i].className = "";//清除按钮的样式
}
this.btnLis[this.index].className = "active";
},
moveIndex : function(index){//移动index
clearInterval(this.autoTimer);//清楚定时
var posx = this.oo.v==0 ? -this.index*this.oo.width : 0,
posy = this.oo.v==1 ? -this.index*this.oo.height : 0,
that = this;
this.Timer = setInterval(function(){that.moveTo(posx, posy)}, 10);
},
moveTo : function(posx, posy){//移动坐标
var left = parseInt(this.$(this.id).style.left),
top = parseInt(this.$(this.id).style.top);
left = left>posx ? left-Math.ceil((left-posx)/10) : left+Math.ceil((posx-left)/10);//当目标位置大于当前位置的时候,一次移动LEFT坐标
top = top>posy ? top-Math.ceil((top-posy)/10) : top+Math.ceil((posy-top)/10);
this.$(this.id).style.top = top + "px";
this.$(this.id).style.left = left + "px";
if(left==posx && top==posy){
clearInterval(this.Timer);
this.index++;
...