一、Demo
<1>.要求
1.鼠标不在图片上方时,进行自动轮播,并且左右箭头不会显示;
当鼠标放在图片上方时,停止轮播,并且左右箭头会显示;
2.图片切换之后,图片中下方的小圆点会同时进行切换,并且点击相应的小圆点可以切换到相应的图片上;
3.点击左右箭头可以进行左右图片的切换;
4.图片上需有介绍的文字,会随图片切换一起进行切换。
<2>.功能
上传多张图片,就像幻灯片一样,用户可以去滑动的,可以更好的展示商品的个性和优点。
二、实现原理
一、箭头的显示可通过css的hover来实现;
二、JS部分主要负责记录图片和清楚图片,从而实现图片的周期性变化
三、代码
<1>.Html部分
<!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>轮播图效果</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div class="container">
<span>Apex Legends</span>
<img class="on" src="./Img/1.jfif">
<img src="./Img/2.jfif">
<img src="./Img/3.jfif">
<img src="./Img/4.jfif">
<div class="left"><</div>
<div class="right">></div>
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script src="./index.js"></script>
</body>
</html>
<2>.Css部分
*{
margin: 0;
padding: 0;
}
.container{
width: 600px;
height: 330px;
position: relative;
top: 100px;
left: 30%;
/*border: 1px solid #000;*/
}
span{
position: absolute;
z-index: 100;
font-size: 30px;
color: #fff;
}
.container img{
position: absolute;
width: 100%;
height: 100%;
transition-duration: 0.5s; /*设置过渡时间*/
opacity: 0; /*把所有图片变透明*/
}
/*图片显示开关*/
.container img.on{
opacity: 1; /*用于显示图片*/
}
.left, .right{
position: absolute;
top: 20%;
width: 30px;
height: 100px;
line-height: 100px;
background-color: #666;
opacity: 0.5;
text-align: center;
font-size: 30px;
color: #ccc;
display: none; /*设置隐藏按钮*/
cursor: pointer;
}
.left{
left: 0;
}
.right{
right: 0;
}
.container:hover .left, .container:hover .right{
display: block; /*取消隐藏按钮设置*/
}
.left:hover, .right:hover{
color: #fff;
}
.container ul{
position: absolute;
bottom: 0;
max-width: 500px;
padding: 5px 200px;
margin-left: 30px;
}
.container ul li{
list-style: none;
float: left;
background-color: #ccc;
width: 10px;
height: 10px;
border-radius: 50%;
margin-left: 10px;
cursor: pointer;
margin-left: 20px;
}
.container ul li.active{
background-color: #282923;
}
<3>.Js部分
//获取标签
var img = document.querySelectorAll('img');
var li = document.querySelectorAll('li');
var btnLeft = document.querySelector('.left');
var btnRight = document.querySelector('.right');
//点击按钮图片切换
var index = 0; //当前图片下标
var lastIndex = 0;
btnRight.onclick = function(){
//记录上一张图片的下标
lastIndex = index;
//清除上一张图片的样式
img[lastIndex].className = '';
li[lastIndex].className = '';
index++;
index %= img.length; //实现周期性变化
//设置当前图片的样式
img[index].className = 'on';
li[index].className = 'active';
}
//左边按钮设置
btnLeft.onclick = function(){
//记录上一张图片的下标
lastIndex = index;
//清除上一张图片的样式
img[lastIndex].className = '';
li[lastIndex].className = '';
index--;
if (index < 0) {
index = img.length - 1;
}
//设置当前图片的样式
img[index].className = 'on';
li[index].className = 'active';
}
四、效果展示
轮播图效果