Native JS achieve image carousel effect diagram

	//css代码
	<style>
		#window{width:800px;border:2px dashed red;
		position: relative;height: 450px;
		margin:100px auto;
		overflow: hidden;
		}
		#img{position: absolute;width:4000px;}
		img{width:800px;float: left;}
		#list{position: absolute;right:10px;bottom:10px;z-index: 9999;}
		#list span{width:20px;height:20px;display: inline-block;
		margin:10px;background: gray;border-radius: 50%;}
		#list .bg{background: #000;}
		#left,#right{position: absolute;font-size:100px;
		line-height: 425px;color: red;}
		#right{right:20px;}
	</style>
		
		//html代码
	<div id='window'>
		<div id="img" style="left:0">
			<img src="img/img1.jpg"/>
			<img src="img/img2.jpg"/>
			<img src="img/img3.jpg"/>
			<img src="img/img4.jpg"/>
			<img src="img/img5.jpg"/>
		</div>
		<div id="list">
			<span></span>
			<span></span>
			<span></span>
			<span></span>
			<span></span>
		</div>
		<a id="left">&lt;</a>
		<a id="right">&gt;</a>
	</div>
		//js代码
		<script>
			var win=document.getElementById('window');//显示窗口
			var imgBox=document.getElementById('img');//胶卷
			var img=imgBox.getElementsByTagName('img');
			var list=document.getElementById('list');
			var ospan=list.getElementsByTagName('span');//所有的序号
			var left=document.getElementById('left');
			var right=document.getElementById('right');
			var w=800;
	//		img[0].offsetWidth
			console.log(w);
			var index=0;
		/*
		 通过改变图片盒子的位置,实现图片轮播
		 1.获取所有相关的元素
		 2.单击切换
		 * */
		
		right.onclick=rightBtn;
		function rightBtn(){
			index++;
			if(index>ospan.length-1){
			//if(index>4)
				index=0;
			}
			fn();
			var newRight;
			/*if(parseInt(imgBox.style.left)==-3200){*/
			if(parseInt(imgBox.style.left)==-imgBox.offsetWidth+w){
				newRight=0;
			}else{
				newRight=parseInt(imgBox.style.left)-w;
			}
			imgBox.style.left=newRight+'px';
		}
		left.onclick=function(){
			index--;
			if(index<0){
				index=ospan.length-1;
			}
			fn();
			var newLeft;
			if(parseInt(imgBox.style.left)==0){
				newLeft=-imgBox.offsetWidth+w;
//					newLeft=-3200;
			}else{
				newLeft=parseInt(imgBox.style.left)+w;
				//newLeft=parseInt(imgBox.style.Left)+800;
			}
			imgBox.style.left=newLeft+'px';
		}
		
		function fn(){
			for(var i=0;i<ospan.length;i++){
				ospan[i].className='';	
			}
			ospan[index].className='bg';
		}
		fn();
		var timer;
		function setTime(){
			timer=setInterval(function(){
				rightBtn();
			},2000);
		}
		setTime();
		win.onmouseenter=function(){
			clearInterval(timer);
		}
		win.onmouseleave=function(){
			setTime();
		}
		for(var n=0;n<ospan.length;n++){
			ospan[n].num=n;//创建一个属性,替换下标存在
			ospan[n].onclick=function(){
				var xiabiao=this.num;
				imgBox.style.left=xiabiao*-w+'px';
				index=xiabiao;
				fn();
			}
		}
		</script>

Guess you like

Origin blog.csdn.net/sneer_shen/article/details/94739420