<!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>
<style>
*{
margin:0;
padding: 0;
list-style: none;
}
img{
width: 100%;
height: 500px;
display: block;
}
.banner{
width:100%;
height:500px;
margin: 50px 0 ;
position:absolute;
}
.first>li{
width:100%;
height:100%;
position:absolute;
left:0;
right:0;
opacity: 0;
transform: opacity 0.5s linear;
}
.banner>ul>li.active{
opacity: 1;
}
.banner>ol{
width: 100px;
height: 20px;
position:absolute;
left:30px;
bottom: 30px;
background-color: rgba(0,0,0,0.5);
display: flex;
justify-content: space-around;
align-items: center;
border-radius: 15px;
}
.banner>ol>li{
width: 10px;
height: 10px;
background-color: wheat;
border-radius: 50%;
cursor:pointer;
}
.banner>ol>li.active{
background-color: red;
}
.right{
width: 50px;
height: 50px;
color:white;
font-size: 40px;
text-align: center;
position: absolute;
right: 0px;
top:50%;
background-color: rgba(0,0,0,0.5);
display: flex;
}
.left{
width: 50px;
height: 50px;
color:white;
font-size: 40px;
text-align: center;
position: absolute;
left: 0px;
top:50%;
background-color: rgba(0,0,0,0.5);
display: flex;
}
</style>
</head>
<body>
<div class ='banner'>
<!--图片区域-->
<ul class = 'first'>
<li class = 'active'><img src="01.jpg" alt=""></li>
<li><img src="02.jpg" alt=""></li>
<li><img src="03.jpg" alt=""></li>
<li><img src="04.jpg" alt=""></li>
</ul>
<!--焦点按钮区域-->
<ol class="second">
<li class = 'active' id = '0'></li>
<li id = '1'></li>
<li id = '2'></li>
<li id = '3'></li>
</ol>
<!--左右按钮区域-->
<div class="right">></div>
<div class="left"><</div>
</div>
<script>
//绑定事件
var banner = document.querySelector('.banner')
var ul = document.querySelectorAll('ul>li')
var ol = document.querySelectorAll('ol>li')
var right = document.getElementsByClassName('right')
var left = document.getElementsByClassName('left')
console.log(banner)
//绑定点击事件
var index = 0
function change(a){
//如果a = 'true' 转到下一张图片
//如果a = 'false' 转到上一张图片
//如果a = n 转到第n张图片
ul[index].className = ''
ol[index].className = ''
//
if(a == 'true'){
index++
}
else if(a == 'false'){
index--
}
else{
index = a
}
//判断index的值,不能超过索引范围
if(index>=ul.length){
index = 0
}
if(index<0){
index = ul.length-1
}
//显示改变后的图片
ul[index].className = 'active'
ol[index].className = 'active'
}
banner.onclick = function(e){
//获取点击的是哪个事件
if (e.target.className == 'right'){
change('true')
}
else if (e.target.className == 'left'){
change('false')
}
else{
var i =e.target.id - 0
change(i)
}
}
//设置每隔5秒换一张图片
setInterval(function(){change('true')},5000)
</script>
</body>
</html>
编写的时候遇到的问题以及改正
首先,对js获取元素的的函数queryseletor()不够了解
- 获取id=‘box’ : var box = docuent.queryselector(‘#box’)
- 获取 class = ‘box’ :var box= document.queryselector(‘.box’)
- 获取div :var div= document.queryselector(‘div’)
其次是对定时器setIntal()不够了解
该定时器的函数格式是 setInterval(函数, 时间)
函数要重新创建
eg:
setInterval(function(){change(‘true’)},5000)