---
title: "JS图片自动轮换效果实现"
author: "mywebcode"
date: "2014-04-30T00:16:00Z"
tags: []
slug: "js"
draft: false
lastmod: "2014-04-30T09:12:44Z"
id: 2058134
url: "https://mywebcode.iteye.com/blog/2058134"
---

![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)今天不在状态，![安静](http://static.blog.csdn.net/xheditor/xheditor_emot/default/quiet.gif)五一快到了，俺就特想玩了。好了，天色已晚，闲话不多说，看下用javaScript 实现的图片自动轮换效果，先看图片![大笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/laugh.gif)

![](http://img.blog.csdn.net/20140430001122109?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvcGhwNTkyMQ=%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)

下面是具体的代码，还是比较简单的。![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>越狱的囚徒</title>
<style type="text/css">
.content{
	border:3px solid red;
	padding:3px;
	width:500px;
	height:245px;
	position:relative;
}
.content img{
	border:0;
	
}
.content div{
	position:absolute;
	z-index:1000;
	border:2px solid green;
	padding:3px 5px;
	background:#ccc;
}
.content .cur{background:red;color:white;}//当前显示的图片的小方块，红色背景白色字体
</style>
<script type="text/javascript">
var arr=['images/1.jpg','images/2.jpg','images/3.jpg','images/4.gif','images/5.jpg'];
var i=0;
var ob,obk;
function lunhuan(){
	
	if(i>4){//数字大于4就从0开始
		i=0;
	}
	ob=document.getElementById("image1");
	ob.src=arr[i];
	//所有div-0到div-4，背景颜色置灰
	for(var j=0;j<=4;j++){
		document.getElementById("div-"+j).style.backgroundColor='#ccc';
		document.getElementById("div-"+j).style.color='black';
	}
	obk=document.getElementById("div-"+i);
	obk.style.backgroundColor='red';
	obk.style.color='white';
	i++;
}
</script>
</head>
<body onload="window.setInterval(lunhuan,1000);">
<div class="content">
	<img id="image1" src="images/1.jpg"/>
	<div class="cur" id="div-0" style="top:215px;right:128px;">1</div>
	<div id="div-1" style="top:215px;right:98px;">2</div>
	<div id="div-2" style="top:215px;right:68px;">3</div>
	<div id="div-3" style="top:215px;right:38px;">4</div>
	<div id="div-4" style="top:215px;right:8px;">5</div>
</div>
<input type="button" value="test" onclick="lunhuan();"/>
</body>
</html>
```

简单的说下流程：

1.先定义最外层的DIV

2.再定义紧挨着的图片DIV

3.图片右下角的小方块DIV

用计时器函数，实现图片轮换，并让小方块也产生对于的变化。

OK，睡觉。