焦点图广泛运用于主页的醒目位置放置广告,简单好用,加上效果也很好看。


实现的效果:

5张图片每两秒轮播一次,右下角的数字随图片而变换,鼠标放在数字上图片停止,移走鼠标继续播放。

html5图片自动轮播模板 html5图片轮播代码_css


实现步骤:


1.HTML部分

加入一个div,用来放置图片资源和数字编号。

采用ul-li布局,代码如下:


<div id="ad">
	<ul id="ad_img">
    	<li><img src="src/ad1.jpg" width="960" height="600" /></li>
        <li><img src="src/ad2.jpg" width="960" height="600" /></li>
        <li><img src="src/ad3.jpg" width="960" height="600" /></li>
        <li><img src="src/ad4.jpg" width="960" height="600" /></li>
        <li><img src="src/ad5.jpg" width="960" height="600" /></li>
    </ul>
    
    <ul id="ad_num">
    	<li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
</div>

五张图片,五个数字,简单易懂。


2.CSS部分


CSS主要用来处理一下布局的细节,以及写一些类标签方便在js文件中调用。




/*整个广告div的css*/
#ad{
	width:960px;
	height:600px;
	position:absolute;
}
/*取消小圆点*/
#ad li{
	list-style:none;
}

#ad_img li{
	display:none;
}

/*角落显示数字的ul*/
#ad_num{
	overflow:hidden;
	position:absolute;
	bottom:10px;
	right:10px;
	color:#FFF;
}
/*数字的浮动*/
#ad_num li{
	border:#FFF solid 1px;
	float:left;
	margin:0px 5px;
	padding:3px 10px;
}



经过上面的CSS样式的控制,页面显示出来的布局已经达到。





.numsover{
	background-color:#CF3;
	color:#F00;
}

.numsout{}



3.JQuery部分:



jq文件就要控制鼠标时间和自动播放的事件了:






写一个方法用来监听鼠标事件和设置循环时间:



思路如下:



1.获取图片和角标的数组;



2.首先让第一张图片显示出来,并且对应的数字加上CSS效果;



3.监听鼠标事件mouseover()和mouseout(),



在mouseover()中写一个匿名函数,用来控制鼠标移动到数字的li标签上去以后:



(1)把数字加上样式表



(2)把当前的图片隐藏,显示出来鼠标对应的数字索引的图片



在mouseout()中要记得写上把自动轮换的标志设为true;



4.设置轮转事件setInterval(),两个参数分别为



(1)一个匿名函数,用来控制在限定时间后紧接着变换图片和数字的效果



(2)超时时间,单位毫秒。



function changeImg(){
	/*获取图片和索引的数组*/
	var $imgs=$("#ad_img li");
	var $nums=$("#ad_num li");
	
	var isStop=false;
	var index=0;
	
	$nums.eq(index).addClass("numsover");
	$nums.eq(index).siblings().removeClass("numsover");
	$imgs.eq(index).show();
	
	/*鼠标悬停在数字上的事件*/
	$nums.mouseover(function(){
		isStop=true;
		/*先把数字的背景改了*/
		$(this).addClass("numsover").siblings().removeClass("numsover");
		
		/*图片的索引和数字的索引是对应的,所以获取当前的数字的索引就可以获得图片,从而对图片进行操作*/
		index=$nums.index(this);
		$imgs.eq(index).show("slow");
		$imgs.eq(index).siblings().hide("slow");
	}).mouseout(function(){isStop=false});
	/*设置循环*/
	setInterval(function(){
		if(isStop) return;
		if(index>=5) index=-1;
		index++;
		
		$nums.eq(index).addClass("numsover").siblings().removeClass("numsover");
		
		$imgs.eq(index).show("slow");
		$imgs.eq(index).siblings().hide("slow");
		
		},2000);
}

最后在网页加载完调用这个函数,开始执行效果:



$(document).ready(function(e) {
    changeImg();
});