js+css实现简单轮播图效果

js+css实现简单轮播图效果

首先把基本轮播图的界面和样式写好

	<div id="box">
		<img src="11.jpg" alt="" id="pic">
		<ul id="lil">
			<li>1</li>
			<li>2</li>
			<li>3</li>
			<li>4</li>
			<li>5</li>
		</ul>
		<div class="bt" id="left"><<</div>
		<div class="bt" id="right">>></div>
	</div>

css样式如下`:

	*{
		margin: 0;
		padding: 0;
	}
	#box{
		width: 500px;
		height: 300px;
		position: relative;
		margin: 20px auto;
	}
	.bt{
		width: 50px;
		height: 70px;
		background-color:rgba(0,0,0,0.2);
		position: absolute;
		text-align: center;
		line-height: 70px;
		display: none;
	}
	#left{
		left: 0;
		top: 100px;
	}
	#right{
		right: 0;
		top: 100px;
	}
	#lil{position: absolute;bottom: 20px;left: 120px;}
	#lil li{

		float: left;
		width: 20px;
		height: 20px;
		background-color:#aaa;
		list-style: none;
		margin-left: 10px;
		line-height: 20px;
		text-align: center;
	}

这里我们只放了一张图片,但是我们要准备好5张图片进行轮播。 在样式写好后,接下来js如下:

  1. 这里首先让图片轮播起来,因为开始在样式只放了一张图片(ps:这里轮播的图片名字我是11.jpg,22.jpg,33.jpg)所以通过定时器的设置让图片的src进行改变,以此来轮播,在轮播的同时对应小圆点也一同变化。
var li=document.getElementsByTagName('li');
	var box=document.getElementById("box");
	var pic=document.getElementById("pic");
	var left=document.getElementById("left");
	var right=document.getElementById("right");


	li[0].style.backgroundColor="red";
	var aa=0;
	var cen=11;
	var timer=setInterval(star,1000);
	function star(){

		cen=cen+11;
		aa++
		func();
	}
	function func(){
		if (cen==66) {
			cen=11;
			aa=0;
		}
		else if(cen==0){
			cen=55;
			aa=4;
		};
		pic.src=cen+".jpg"

		for(var i=0;i<li.length;i++){
			li[i].style.backgroundColor="#aaa";
		}
		li[aa].style.backgroundColor="red";
	}
	box.addEventListener("mouseover",over,false);
	function over(){
		clearInterval(timer);
		left.style.display="block";
		right.style.display="block";
	}
	box.addEventListener("mouseout",start,false);
	function start(){
		 timer=setInterval(star,1000);
		 left.style.display="none";
		 right.style.display="none";
	}

2.然后设置左右两个按钮的控制功能

left.addEventListener("mouseover",deep,false);
	right.addEventListener("mouseover",deep,false);
	function deep(){
		this.style.backgroundColor="rgba(0,0,0,0.6)";
	}
	left.addEventListener("mouseout",nodeep,false);
	right.addEventListener("mouseout",nodeep,false);
	function nodeep(){
		this.style.backgroundColor="rgba(0,0,0,0.2)";
	}
	left.addEventListener("click",function(){
		cen=cen-11;
		aa--;
		func();
	},false)
	right.addEventListener("click",function(){
		cen=cen+11;
		aa++;
		func();
	},false)

3.最后设置小圆点的控制功能,当鼠标点击小圆点时跳到对应图片,并停止轮播

for (var i = 0; i < li.length; i++) {
		li[i].index=i*11+11;

		console.log(li[i].index)

		li[i].addEventListener("mouseover",function(){
			
			cen=parseInt(this.index);
			aa=parseInt((this.index)/10-1);

			func();

		},false);

最后结果:
轮播图

你可能感兴趣的:(html,html,javascript,css)