淡入淡出式轮播

小生是个萌新 最近弄了一个淡入淡出式轮播 拿出来分享一下
技术不好 还请大家多多包涵

html部分

<div id="carousel">
		<img src="images/1.jpg" alt="" class="on">
		<img src="images/2.jpg" alt="">
		<img src="images/3.jpg" alt="">
		<img src="images/4.jpg" alt="">
		<img src="images/5.jpg" alt="">
		<ul id="switchBtn">
			<li ind="1" class="hover"></li>
			<li ind="2"></li>
			<li ind="3"></li>
			<li ind="4"></li>
			<li ind="5"></li>
		</ul>
	</div>

css部分

		*{
			margin: 0;
			padding: 0;
		}
		ul,li{
			list-style:none;
		}
		img{
			display: block;
		}
		#carousel{
			width: 960px;
			height: 275px;
			margin: 100px auto;
			position: relative;
			border: 1px solid #eee;
		}
		#carousel img{
			width: 960px;
			height: 275px;
			position: absolute;
			opacity: 0;
			animation-timing-function: linear;
			animation-duration:0.5s;
			animation-fill-mode:forwards;
		}
		#carousel img.on{
			animation-name: on;
		}
		#carousel img.hide{
			animation-name: conceal;
		}
		@keyframes on{
			from{opacity;}
			to{opacity:1;}
		}
		@keyframes conceal{
			from{opacity:1;}
			to{opacity:0;}
		}
		#switchBtn{
			width: 125px;
			height: 20px;
			position: absolute;
			right: 50px;
			bottom: 20px;
		}
		#switchBtn li{
			float: left;
			width: 20px;
			height: 20px;
			background:#988F8F;
			margin-right: 5px;
			border-radius: 50%;
		}
		#switchBtn li.hover{
			background: #0379F5;
		}

js部分

		var timer = null;
		var index = 0;
		var ind = 1;
		window.onload = function(){
			var carousel = document.getElementById("carousel").getElementsByTagName("img");
			var switchBtn = document.getElementById("switchBtn").getElementsByTagName("li");
			var prev = document.getElementById("prev");	
			var next = document.getElementById("next")
			
			//调用自动播放函数
			autoPlay();
			
			//鼠标移入停止播放
			carousel.onmouseover = stop;
			
			//鼠标移出继续播放
			carousel.onmouseout = autoPlay;
			
			//圆点导航高亮效果
			for(var i=0;i<switchBtn.length;i++){
				(function(j){
					switchBtn[j].onmouseover = function(){
						setImg(j);
						index = j;
					}
				})(i);
			}
			
		}

图片切换函数

//图片切换函数
		function setImg(offset){
			var carousel = document.getElementById("carousel").getElementsByTagName("img");
			var switchBtn = document.getElementById("switchBtn").getElementsByTagName("li");
			for(var i=0;i<switchBtn.length;i++){
				carousel[i].className ="hide";
				switchBtn[i].className = "";
			}
			carousel[offset].className = "on";
			switchBtn[offset].className = "hover";
		}

自动播放函数与停止播放

//自动播放函数
		function autoPlay(){
			var switchBtn = document.getElementById("switchBtn").getElementsByTagName("li");
			timer = setInterval(function(){
				index++;
				if(index>=switchBtn.length){
					index = 0;
					
				}
				setImg(index);
			},2000);
		}
		
		//停止播放
		function stop(){
			clearInterval(timer);
		}

猜你喜欢

转载自blog.csdn.net/weixin_44561804/article/details/86535534