轮播图
我们在很多网站上面都能看到一些轮播图,很炫酷,那么我们也可以除了利用组件写好的轮播,我们也可以自己手动写轮播,如下所示:
1:css部分
css部分就是将几张图片放在一个盒子里面,设置显示和隐藏等
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./jquery-3.4.1.js"></script>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,body{
width: 100%;
height: 100%;
}
.wrap{
width: 800px;
height: 400px;
position: relative;
top: 0;
left: 30%;
margin-top: 50px;
/* border: 1px solid red; */
}
.wrap .pic{
width: 800px;
height: 400px;
display: flex;
}
.wrap .pic li{
width: 800px;
height: 400px;
display: none;
}
.wrap .pic li.active{
display: block;
}
.wrap .pic li img{
width: 800px;
height: 400px;
/* margin: 50px; */
}
ul,li{
list-style: none;
}
.indicator{
width: 20%;
height: 30px;
position: absolute;
/* border: 1px solid red; */
display: flex;
left: 40%;
bottom: 50px;
}
.indicator li{
width: 15px;
height: 15px;
border-radius: 50%;
background-color: grey;
margin: 5px;
}
.indicator li.current{
background-color: blue;
}
.next{
color: white;
font-size: 40px;
position: absolute;
top: 40%;
right: 10px;
background-color: rgba(0,0,0,0.5)
/* display: none; */
}
.prev{
color: white;
font-size: 40px;
position: absolute;
top: 40%;
left: 10px;
background-color: rgba(0, 0, 0, 0.5)
/* display: none; */
}
</style>
</head>
<body>
<div class="wrap">
<ul class="pic">
<li class="active">
<img src="./img/0.png" alt="">
</li>
<li>
<img src="./img/1.png" alt="">
</li>
<li>
<img src="./img/2.png" alt="">
</li>
<li>
<img src="./img/3.png" alt="">
</li>
</ul>
<ul class="indicator">
<li class="current"></li>
<li></li>
<li></li>
<li></li>
</ul>
<!-- 下一张图片 -->
<div class="next">></div>
<!-- 上一张图片 -->
<div class="prev"><</div>
</div>
</body>
</html>
2:js部分:
js部分的代码思路就是根据索引值将当前的那张图片加上一个类名active,(active设置了图片显示),其他的移除类名,再绑定指示灯的索引值,这样也能根据指示灯来切换图片。
<script>
var index = 0
// 展示图片和索引
function showImg () {
// 显示当前图片,隐藏其他图片
$('.pic li').eq(index).addClass('active').siblings().removeClass('active');
// 给当前索引添加红色背景
$('.indicator li').eq(index).addClass('current').siblings().removeClass('current');
}
// 下一张图
function nextImg(){
index++;
if(index==$('.pic li').length){
index = 0;
}
// index ++;
showImg();
}
// 上一张图
function prevImg () {
index--
if(index==-1){
index = $('.pic li').length-1;
}
showImg();
}
// 点击上一张切换
$('.prev').click(function(){
prevImg()
})
// 点击下一张切换
$('.next').click(function(){
nextImg()
})
// 自动切换
var timer = setInterval(nextImg,1000);
// 点击指示灯切换
$('.indicator li').hover(function(){
index = $(this).index();
showImg();
})
// 鼠标进来停止切换
$('.wrap').hover(function(){
clearInterval(timer)
},function(){
timer = setInterval(nextImg,1000);
})
</script>
谢谢,下次我们将介绍另一种轮播图的方法