用html+css和简单的js代码,实现一个有导航栏的原生js动态轮播图。
- 自己动手用原生js写了一个简单的轮播图,js代码只有40多行,没有复杂的逻辑和各种难懂的函数,对初学者和小白比较友好。
- 主功能要逻辑有:1.鼠标划过整个容器时停止自动播放,2.鼠标离开整个容器时继续播放至下一张,3. 遍历所有数字导航实现划过切换至对应的图片,4.创造图片切换函数,实现轮播图的隐藏和展示。
- 为了方便阅读和理解,我把一个完整的代码拆成了HTML,css,js三部分展示,代码中配有比较详细的注释。需要用时,直接复制粘贴各部分代码,再结合起来用即可。
- 最后,我再提供一个极简的js轮播图代码,用几行代码就实现图片动起来。欧力给!!
html部分代码,有个div包裹整个轮播图
<div id="wrap">
<!-- 轮播图片 -->
<div>
<ul id="pic">
<li><img src="./IMAGE/xy-1.jpg" alt="图片" /></li>
<li><img src="./IMAGE/xy-2.jpg" alt="图片" /></li>
<li><img src="./IMAGE/xy-3.jpg" alt="图片" /></li>
<li><img src="./IMAGE/xy-4.jpg" alt="图片" /></li>
<li><img src="./IMAGE/xy-5.jpg" alt="图片" /></li>
</ul>
</div>
<!-- 图片导航数 -->
<div>
<ol id="list">
<li class="on">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
</div>
</div>
css代码块部分
<!-- css -->
<style>
#wrap {
height: 320px; /* 给轮播图设置整体高度 */
overflow: hidden; /* 超出部分隐藏*/
margin: 0 auto; /* 居中 */
position: relative; /* 子绝父相 */
width: 100%;
}
#pic {
width: 100%; /*让图片占满整个页面*/
}
#pic li img {
width: 100%;
height: 100%;
z-index: -1;
}
#list {
position: absolute; /* 子绝父相 */
bottom: 10px;
right: 5px;
}
#list li {
list-style: none;
float: left;
/* 设置正方形边框 */
height: 20px;
width: 20px;
background: #ccc;
color: #000;
border-radius: 5px;
text-align: center;
margin-left: 5px;
cursor: pointer;
}
/* 轮播到当前导航栏 */
#list .on {
background: #e97305;
color: #fff;
}
</style>
js代码块部分。图片切换函数changePic(),自动播放函数autoPlay()
<!-- js -->
<script>
window.onload = function() {
//获取属性
var wrap = document.getElementById("wrap"),
pic = document.getElementById("pic").getElementsByTagName("li"),
list = document.getElementById("list").getElementsByTagName("li"),
index = 0, //检索初值为0
timer = null; // 先把定时器清空
// 定义并调用自动播放函数
timer = setInterval(autoPlay, 2000);
// 鼠标划过整个容器时停止自动播放
wrap.onmouseover = function() {
clearInterval(timer);
};
// 鼠标离开整个容器时继续播放至下一张
wrap.onmouseout = function() {
setInterval(autoPlay, 2000);
};
// 遍历所有数字导航实现划过切换至对应的图片
for (var i = 0; i < list.length; i++) {
list[i].onmouseover = function() {
clearInterval(timer); //暂停轮播
index = pic.length; //给检索赋值
changePic(index); //切换到对应图片
};
}
//自动播放函数
function autoPlay() {
if (++index >= pic.length) index = 0; //超出图片数,则回到第一张
changePic(index); //调用切换函数
}
//创造图片切换函数,curIndex为形参
function changePic(curIndex) {
for (var i = 0; i < pic.length; ++i) {
pic[i].style.display = "none"; //隐藏图片
list[i].className = ""; //导航条
}
pic[curIndex].style.display = "block"; //展示图片
list[curIndex].className = "on";
}
};
</script>
最后,这是极简版代码,实现图片轮播
var pic = document.getElementById("pic").getElementsByTagName("li"),
index = 0;
function auto() {
for (var i = 0; i < pic.length; i++) {
pic[i].style.display="none" ;
};
pic[index].style.display="block" ;
if (++index>= pic.length) index = 0;
}
setInterval(auto, 2000);