今天帅帅学到了js部分就想简单的做一个小的轮播图,在网上也看过别人写的,决定自己尝试下–>>>
样例展示:图片需要自己替换:
html部分:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<link rel="stylesheet" type="text/css" href="lunbo.css"/>
<script src="lunbo.js">
</script>
</head>
<body>
<div id="lunbo">
<ul id="pic">
<li><img src="2.jpg"/></li>
<li><img src="3.jpg"/></li>
<li><img src="4.jpg"/></li>
<li><img src="5.jpg"/></li>
<li><img src="6.jpg"/></li>
</ul>
<ol id="list">
<li class="on">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol
</div>
</body>
</html>
css部分
*{
margin: 0;
padding: 0;
}
div{
margin: 20% auto;
width: 500px;
height: 309px;
border: 1px solid black;
position:relative;
overflow:hidden;
}
ul {
list-style: none;
position:absolute;
}
ul li{
float: left;
}
ol {
position: absolute ;
bottom: 5px;
left: 157px;
}
ol li{
background:#ddd;
border:1px solid #969591;
height:20px;
width:20px;
border-radius:50%;
margin-left:10px;
color:#959490;
float:left;
text-align:center;
cursor:pointer;
list-style: none;
}
.on{
background:#8F9E9E;
color:#fff;
}
js部分
window.onload = function() {
var wrap = document.getElementById('lunbo'),
pic = document.getElementById('pic'),
list = document.getElementById('list').getElementsByTagName('li'),
index = 0,
timer = null;
// 若果有在等待的定时器,则清掉
if (timer) {
clearInterval(timer);
timer = null;
}
// 自动切换
timer = setInterval(autoPlay, 2000);
// 定义并调用自动播放函数
function autoPlay() {
index++;
if (index >= list.length) {
index = 0;
}
changeImg(index);
}
// 定义图片切换函数
function changeImg(curIndex) {
for (var j = 0; j < list.length; j++) {
list[j].className = "";
}
// 改变当前显示索引
list[curIndex].className = "on";
pic.style.marginTop = -318 * curIndex + "px";
index = curIndex;
}
// 鼠标划过整个容器时停止自动播放
wrap.onmouseover = function() {
clearInterval(timer);
}
// 鼠标离开整个容器时继续播放至下一张
wrap.onmouseout = function() {
timer = setInterval(autoPlay, 2000);
}
// 遍历所有数字导航实现划过切换至对应的图片
for (var i = 0; i < list.length; i++) {
list[i].id = i;
list[i].onmouseover = function() {
clearInterval(timer);
changeImg(this.id);
}
}
}