html代码:
<div id="playBox" class="play-box">
<div id="imgList">
<a href="http://www.baidu.com" target="_blank" class="current">
<img src="/img/1.png" alt="">
</a>
<a href="http://www.baidu.com" target="_blank">
<img src="/img/2.png" alt="">
</a>
<a href="http://www.baidu.com" target="_blank">
<img src="/img/3.jpg" alt="">
</a>
<a href="http://www.baidu.com" target="_blank">
<img src="/img/4.jpg" alt="">
</a>
</div>
<div class="iconList">
<ul>
<li class="current">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<div class="slidebar slidebar-left"><</div>
<div class="slidebar slidebar-right">></div>
</div>
css代码:
body {
margin: 0;
padding: 0;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
.play-box {
position: relative;
margin: 100px auto;
width: 520px;
height: 280px;
border: 1px solid #ccc;
overflow: hidden;
}
.play-box a {
display: block;
opacity: 0;
height: 0;
transition: opacity .5s;
}
.play-box a.current {
opacity: 1;
height: auto;
}
.play-box img {
width: 520px;
height: 280px;
}
.iconList {
position: absolute;
bottom: 10px;
left: 50%;
margin-left: -45px;
}
.iconList li {
width: 10px;
height: 10px;
border-radius: 50%;
font-size: 0;
background: #fff;
cursor: pointer;
float: left;
margin: 0 4px;
}
.iconList li.current {
background-color: orange;
}
.slidebar {
display: none;
position: absolute;
top: 50%;
margin-top: -25px;
width: 30px;
height: 50px;
color: #fff;
background-color: #000;
text-align: center;
line-height: 50px;
opacity: .6;
cursor: pointer;
}
.slidebar-left {
left: 0;
}
.slidebar-right {
right: 0;
}
js代码:
$(document).ready(function(){
let speed = 2000;
let m = 1;//显示第几张图片
//控制显示图片、图标函数
let controlPlay = (n) => {
//console.log(n);
//img
$("#imgList a").removeClass("current").eq(n).addClass("current");
//icon
$(".iconList li").removeClass("current").eq(n).addClass("current");
}
//让图片自己动起来函数
let runPlay = () => {
if(m > 3) {
m = 0;
}
//console.log(m);
controlPlay(m);
m ++;
}
//函数执行
let playTimer = setInterval(runPlay, speed);
//整个轮播图的鼠标悬停事件
$("#playBox").mouseenter(function(){
//停止
clearInterval(playTimer);
//左右控制按钮显示
$(".slidebar").fadeIn(300);
return false;
}).mouseleave(function(){
//重新开始
playTimer = setInterval(runPlay, speed);
//左右控制按钮隐藏
$(".slidebar").fadeOut(300);
return false;
});
//给li控制图标绑定单机事件
$(".iconList li").click(function() {
controlPlay($(this).index());
m = $(this).index() + 1;
})
//点击切换下一张图片
$(".slidebar-right").click(function() {
if(m > 3) {
m = 0;
}
//显示下一张
controlPlay(m);
//m变化
m ++;
})
//点击切换上一张
$(".slidebar-left").click(function() {
m -= 2;
if(m < 0) {
m = 3;
}
//显示下一张
controlPlay(m);
//m变化
m ++;
})
})