JS—轮播图

效果图如上,代码如下:

HTML部分:

<div class="wrap">
     <div class="imgs">
          <img style="opacity:1" src="img/img2.jpg"/>
          <img src="img/img3.jpg"/>
          <img src="img/img4-1.jpg"/>
          <img src="img/img1.jpg"/>
     </div>
     <div class="lBtn"> < </div>
     <div class="rBtn"> > </div>
     <ul>
          <li>1</li>
          <li>2</li>
          <li>3</li>
          <li>4</li>
      </ul>
</div>

接下来就是CSS部分了,看起来更加美观:

*{margin:0;padding:0}
.wrap{width:590px;height:470px;margin:50px auto;position:relative}
.wrap .imgs{width:590px;height:470px;position:relative}
.wrap .imgs img{width:590px;height:470px;position:absolute;opacity:0}
.wrap .lBtn{width:50px;height:30px;line-height:30px;text-align:center;position:absolute;top:220px;left:0;background:rgba(204,204,204,0.5);cursor:pointer}
.wrap .rBtn{width:50px;height:30px;line-height:30px;text-align:center;position:absolute;top:220px;right:0;background:rgba(204,204,204,0.5);cursor:pointer}
.wrap ul{width:120px;height:30px;position:absolute;left:0;top:400px;right:0;bottom:0;margin:auto;}
.wrap ul li{height:30px;width:30px;background:#CCC;line-height:30px;text-align:center;border-radius:50%;list-style:none;float:left;color:#fff;cursor:pointer}
.wrap .on{background:#333}

最后就是效果实现的部分了,js代码如下:

//先获取DOM元素
var wrap=document.getElementsByClassName("wrap")[0] //获取大盒子
var img=wrap.getElementsByClassName("imgs")[0].getElementsByTagName("img")//获取图片
var lBtn=wrap.getElementsByClassName("lBtn")[0]//获取左按钮
var rBtn=wrap.getElementsByClassName("rBtn")[0]//获取右按钮
var li=wrap.getElementsByTagName("li")//获取li
var index=0;//下标
//初始状态,也就是第一个有样式
li[0].className="on"
//点击左右按钮以及底部按钮实现图片的切换
//左按钮
lBtn.οnclick=function(){
	if(index==0){
		index=img.length-1
	}else{
		index--
	}
	//切换
	tab()
}
//右按钮
rBtn.οnclick=function(){
	if(index>=img.length-1){
		index=0
	}else{
		index++
	}	
	//切换
	tab()	
}
//底部圆按钮
for(var i=0;i<li.length;i++){
	li[i].index=i;
	li[i].οnclick=function(){
		index=this.index
		//切换
		tab()
	}
}
//图片切换方法
//切换
function tab(){
	//所有的img隐藏,对应的显示	;所有的li不变色,对应的li变色
	for(var i=0;i<li.length;i++){
		//DomUtil.startMove(img[i],{opacity:0})
		img[i].style.display="none"
		li[i].className=""
	}
	img[index].style.display="block"
	//DomUtil.startMove(img[index],{opacity:100})
	li[index].className="on"
}

//图片自动轮播效果
var timer=setInterval(function(){
	if(index>=img.length-1){
		index=0
	}else{
		index++
	}	
	//切换
	tab()
},2000)	

//鼠标划上,停止计时,轮播图片停止
wrap.οnmοuseοver=function(){
	clearInterval(timer)
}
//鼠标划出,恢复原样
wrap.οnmοuseοut=function(){
	timer= setInterval(function(){
		if(index>=img.length-1){
			index=0
		}else{
			index++
		}	
		//切换
		tab()
	},2000)
}
setInterval(tab,2000)	


发布了8 篇原创文章 · 获赞 6 · 访问量 320

猜你喜欢

转载自blog.csdn.net/yadibaibai/article/details/104070208