<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
*{
margin:0;
padding:0;
}
ol,ul{list-style:none;}
.box{
margin:0 auto;
width:500px;
position: relative;
cursor: pointer;
}
.box ul{
width:500px;
height:300px;
}
.box ul li{
width:100%;
height: 100%;
position:absolute;
top:0;
left:0;
opacity:0;
transition:opacity 0.5s linear;
}
.box ul li img{
width:100%;
height:100%;
}
.box ul .on{
opacity:1;
z-index:1;
}
.box ol{
position:absolute;
bottom:20px;
left:50%;
margin-left:-75px;
z-index: 2;
}
.box ol li{
float: left;
width:25px;
height:25px;
background:rgba(0,0,0,0.5);
border-radius:50%;
margin-right:5px;
cursor: pointer;
}
.box ol .yd{
background:rgba(0,0,0,0.9);
}
.prev,.next{
position:absolute;
top:50%;
margin-top:-40px;
width:50px;
height:80px;
background:rgba(0,0,0,0.5);
font-family: "宋体";
text-align: center;
line-height:80px;
color:#fff;
font-size:25px;
font-weight:bolder;
cursor: pointer;
z-index: 2;
}
.prev:hover ,.next:hover {
background:rgba(0,0,0,0.9);
}
.next{right:0;}
.prev{left:0;}
</style>
<body>
<div class="box">
<ul>
<li><img src="img/1.jpg" alt=""></li>
<li><img src="img/2.jpg" alt=""></li>
<li><img src="img/3.jpg" alt=""></li>
<li><img src="img/4.jpg" alt=""></li>
<li><img src="img/5.jpg" alt=""></li>
</ul>
<!-- 圆点 -->
<ol>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
<!-- 左右箭头 -->
<span class="prev"><</span><span class="next">></span>
</div>
</body>
<script>
var box = document.querySelector(".box");
var aLi = document.querySelectorAll(".box ul li");
var oLi = document.querySelectorAll(".box ol li");
var prev = document.querySelector(".prev");
var next = document.querySelector(".next");
var index = 0; //初始下标
var tt = null; //定时器
tab()
// 创建一个样式重置函数
function tab(){
for(var i = 0;i < aLi.length;i ++){
aLi[i].classList.remove("on") // 不为index项的图片 透明度默认为0
oLi[i].classList.remove("yd") // 不为index的小圆点背景默认
}
// 只有第index项添加on类名 on类名在css样式中代表透明度为1
aLi[index].classList.add("on")
// 为index的小圆点背景加深
oLi[index].classList.add("yd")
}
// 下一张图片按钮 每点击一次
next.onclick=function(){
index ++ // index 会进行累加
if(index > aLi.length-1) { //当index的数值大于li的长度-1 会回到0
index = 0;
}
tab()
}
prev.onclick=function(){
index -- // index进行累减
if(index < 0) {
index = aLi.length-1
}
tab()
}
for(var i = 0;i < oLi.length; i ++){
oLi[i].xb=i
oLi[i].onclick=function(){
index = this.xb
tab()
}
}
function _time(){
clearInterval(tt)
tt = setInterval(function(){
next.click()
},2000)
}
_time()
box.onmouseover=function(){
clearInterval(tt)
}
box.onmouseout=_time;
</script>
</html>
原生JS创建轮播图
最新推荐文章于 2024-09-02 17:34:07 发布