JavaScript原生代码手写轮播图
代码思路
- 获取到对应的标签
- 设定两个全局变量,当前索引index和上一索引 lastIndex
- 封装清除和添加 class属性 , 上一索引对的图片按钮清除class,当前添加class,实现切换效果
- 给btn按钮添加点击事件
- 给向左,向右点击添加事件,实现点击切换
- 这里需要对index的值进行判断,最大值为length-1,最小值为0;
- 如果index值大于length-1,index=0;如果index小于0,index=length-1;
- 封装自动轮播函数
- 封装鼠标移入停止,移出继续轮播函数
<style>
*{padding: 0;margin: 0;}
ul,ol,li{list-style: none;}
a{text-decoration: none;}
img{display: block;}
.clear::after{content: ""; clear: both; display: block;}
#banner{
width: 850px;
height: 500px;
margin: 50px auto;
overflow: hidden;
position: relative;
cursor: pointer;
}
#pic li{
width: 850px;
height: 500px;
position: absolute;
left: 0;
top: 0;
background: #fcc;
font-size: 40px;
text-align: center;
line-height: 500px;
color: white;
z-index: 0;
transition: opacity 1.5s;
}
#pic li.active{
z-index: 5;
opacity: 1;
}
#btns{
position: absolute;
right: 3%;
bottom: 10px;
z-index: 6;
}
#btns li{
width: 20px;
height: 20px;
background: rgba(0,0, 0,.5);
color: #fcc;
margin-left: 5px;
text-align: center;
line-height: 20px;
float: left;
cursor: pointer;
}
#btns li.active{
background: orange;
color: white;
}
#banner a{
position: absolute;
top: 50%;
margin-top: -10px;
height: 40px;
line-height: 32px;
text-align: center;
width: 40px;
font-size: 40px;
vertical-align: middle;
color: white;
background: rgba(0, 0, 0, .6);
z-index: 6;
}
#goPrev{left: 0;}
#goNext{right: 0;}
</style>
<div id="banner">
<ul id="pic" class="clear">
<li style="background: rgb(212, 12, 12);" class="active">拯救一个人,就是拯救整个世界</li>
<li style="background: rgb(10, 10, 221);">永远都不要忘记你所爱的人</li>
<li style="background: rgb(202, 170, 128);">每个人都要走一条自己坚定的路</li>
<li style="background: rgb(59, 206, 191);">最后那些无聊的事情,才是值得怀恋的</li>
<li style="background: rgb(218, 13, 218);">我们一路奋战不是为了改变世界</li>,
</ul>
<ol id="btns" class="clear">
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
<a href="JavaScript:;" id="goPrev">«</a>
<a href="JavaScript:;" id="goNext">»</a>
</div>
<script>
var div = document.querySelector('#banner');
var imgs = document.querySelectorAll('ul>li');
var btns = document.querySelectorAll('ol>li');
var goPrev = document.querySelector('#goPrev');
var goNext = document.querySelector('#goNext');
var index = 0;
var lastIndex = 0;
function changeImg() {
btns[lastIndex].classList.remove('active');
imgs[lastIndex].classList.remove('active');
btns[index].classList.add('active');
imgs[index].classList.add('active');
}
Array.from(btns).forEach((item,key) => {
item.onclick = function () {
lastIndex = index;
index = key;
changeImg();
}
})
goNext.onclick = function () {
lastIndex = index;
index++;
if(index === imgs.length) index = 0;
changeImg();
}
goPrev.onclick = function () {
lastIndex = index;
index--;
if(index < 0) index = imgs.length-1;
changeImg();
}
autoLoop();
function autoLoop() {
div.time = setInterval(function(){
goNext.onclick();
} , 3000)
}
div.onmouseenter = function() {
clearInterval(div.time);
}
div.onmouseleave = autoLoop;
</script>