JS轮播图所涉及的主要知识点:
- 定时器
- 绝对定位
- 溢出隐藏
- css层叠
CSS代码
#slider {
overflow: hidden; /*溢出隐藏*/
position: relative; /*相对定位为子元素提供参考*/
width: 100%;
height: 520px;
}
/*轮播图片*/
#pic li {
background: url(../images/index/banner_20170725.jpg) no-repeat center;
width: 100%;
height: 520px;
}
#pic li:nth-child(2) {
background: url(../images/index/banner_20170824.jpg) no-repeat center;
}
#pic li:nth-child(3) {
background: url(../images/index/banner_20180827.jpg) no-repeat center;
}
#pic li:nth-child(4) {
background: url(../images/index/banner_20190311.jpg) no-repeat center;
}
/*鼠标移上去显示上一张、下一张 按钮*/
#slider:hover #arrow-left,
#slider:hover #arrow-right{
opacity: 1;
}
/*索引*/
#list {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 3;
width: 78px;
margin-left: -39px;
}
#list li {
cursor: pointer;
background: url(../images/dot.png) no-repeat -18px 2px;
margin: 0 5px 0 0;
float: left;
width: 12px;
height: 12px;
}
#list .on,
#list li:hover{
background: url(../images/dot.png) no-repeat 0 2px;
}
/*按钮*/
#arrow-left,
#arrow-right {
opacity: 0;
cursor: pointer;
background: url(../images/asset\ 35.png);
display: block;
position: absolute;
top: 40%;
left: 15%;
height: 119px;
width: 41px;
}
#arrow-right {
left:85%;
background: url(../images/asset\ 36.png);
}
HTML
<div id="slider">
<ul id="pic">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div id="arrow-left" ></div>
<div id="arrow-right"></div>
<ul id="list">
<li class="on"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
JavaScript
代码重用率比较高,这里没写动画 如果想要酷炫的切换页面可自行添加
window.onload = function () {
var slider = document.getElementById('slider'), //容器
pic = document.getElementById('pic'), //图片列表
list = document.getElementById('list').getElementsByTagName('li'),//索引按钮
picHeight = slider.offsetHeight, //获取图片高度 也可换成offsetWidth
index = 0, //索引
timer = null; //定时器
// 上一张 下一张
var next = document.getElementById("arrow-right");
var prev = document.getElementById("arrow-left");
//下一张
next.onclick = function () {
index++;
if (index >= list.length) { //判断 如果为最后一张 那么下一次跳转到第一张
index = 0;
}
changeImg(index);
}
// 上一张
prev.onclick = function () {
index--;
if (index < 0) { //判断 如果为第一张 那么下一次跳转到最后一张
index = list.length-1;
}
changeImg(index);
}
// 若果有在等待的定时器,则清掉
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 = -picHeight * curIndex + "px";
index = curIndex;
}
// 鼠标划过整个容器时停止自动播放
slider.onmouseover = function () {
clearInterval(timer);
}
// 鼠标离开整个容器时继续播放至下一张
slider.onmouseout = function () {
timer = setInterval(autoPlay, 2000);
}
// 遍历所有数字导航实现划过切换至对应的图片
for (var i = 0; i < list.length; i++) {
list[i].id = i;
list[i].onclick = function () {
clearInterval(timer);
changeImg(this.id);
}
}
}