早些时候分享了淘宝的轮播图,现在让我们一起来看看京东轮播图效果的实现吧,下面是代码:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
#div1 {
width: 850px;
height: 500px;
margin: 50px auto;
overflow: hidden;
position: relative;
}
#div1 ul li {
height: 500px;
opacity: 0;
position: absolute;
left: 0;
top: 0;
z-index: 0;
transition: opacity 1.5s;
}
#div1 ul li.ac {
z-index: 5;
opacity: 1;
}
#div1 ol {
position: absolute;
right: 10%;
bottom: 10px;
z-index: 6
}
#div1 ol li {
width: 15px;
height: 15px;
background: #fff;
margin-left: 5px;
float: left;
line-height: 15px;
text-align: center;
cursor: pointer;
border-radius: 50%;
}
#div1 ol li.ac {
background: deeppink;
/* color: #fff; */
opacity: 0.7;
}
#div1>a {
text-decoration: none;
position: absolute;
top: 50%;
margin-top: -20px;
height: 40px;
line-height: 32px;
text-align: center;
width: 40px;
font-size: 40px;
vertical-align: middle;
color: #fff;
background: rgba(0, 0, 0, 0.6);
z-index: 10;
}
#goPrev {
left: 0;
}
#goNext {
right: 0;
}
img {
width: 850px;
height: 500px;
}
</style>
</head>
<body>
<div id="div1">
<ul>
<li class="ac">
<a>
<img src="pic/001.jpg" />
</a>
</li>
<li>
<a>
<img src="pic/002.jpg" />
</a>
</li>
<li>
<a>
<img src="pic/003.jpg" />
</a>
</li>
<li>
<a>
<img src="pic/004.jpg" />
</a>
</li>
<li>
<a>
<img src="pic/005.jpg" />
</a>
</li>
</ul>
<ol>
<li class="ac"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
<a href="javascript:;" id="goPrev">«</a>
<a href="javascript:;" id="goNext">»</a>
</div>
<script>
// 1 获取节点
let div1Obj = document.getElementById('div1');
let ulLisObj = div1Obj.firstElementChild.children;
let olLisObj = document.querySelectorAll('ol li');
let prevObj = document.getElementById('goPrev');
let nextObj = document.getElementById('goNext');
// 当前图片下标
let index = 0;
// 上一张图片下标
let lastIndex = 0;
let tiems = '';
// 将伪数组转化为数组
//console.log(olLisObj);
Array.from(olLisObj).forEach((li, key) => {
// console.log(val);
li.onclick = function () {
//console.log(key);
// 将index值给lastIndex
lastIndex = index;
// 将当前按钮下标给
index = key
change();
}
});
/****右边按钮,下一张的实现******/
nextObj.onclick = function () {
// 当前索引给lastIndex
lastIndex = index;
index++;
// 判断是否超出最后一张
if (index == ulLisObj.length) index = 0;
change();
}
/*******左边按钮上一张的实现*****/
prevObj.onclick = function () {
lastIndex = index;
index--;
if (index < 0) index = ulLisObj.length - 1;
change();
}
// 自动播放
function autoPlay() {
times = setInterval(() => {
nextObj.onclick();
}, 2000)
}
autoPlay();
// 鼠标移入则停止
div1Obj.onmouseover = () => {
clearInterval(times)
}
div1Obj.onmouseout = () => {
autoPlay();
}
// 当前图片的显示,上一张隐藏
function change() {
// 图片的隐藏显示
ulLisObj[lastIndex].classList.remove('ac');
// 显示当前图片
ulLisObj[index].classList.add('ac');
// // 按钮的显示隐藏
olLisObj[lastIndex].classList.remove('ac')
olLisObj[index].classList.add('ac');
}
</script>
</body>
</html>
感谢观看~~