先看效果
仿京东页面的轮播图
鼠标移入后会暂停轮播,移除后恢复轮播
代码如下:
<!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>
<script src="../js/jquery.js"></script>
<style>
*{
margin: 0;
padding: 0;
}
li{
list-style: none;
}
.box{
position: relative;
margin: 50px auto;
width: 590px;
height: 470px;
text-align: center;
}
.box img{
width: 590px;
height: 470px;
}
ul{
position: absolute;
bottom:10px;
left:20px;
display: flex;
}
li{
margin-right: 10px;
width: 12px;
height: 12px;
border-radius: 50%;
background-color: #fff;
}
.left,.right{
position: absolute;
width: 30px;
height: 30px;
text-align: center;
line-height: 30px;
border-radius: 10px;
background-color: #faf6f6;
}
.left{
left:0;
top:235px;
}
.right{
right:0;
top:235px;
}
.active{
background-color: red;
}
</style>
</head>
<body>
<div class="box">
<img src="../image/lb1.jpg" alt="">
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div class="left"><</div>
<div class="right">></div>
</div>
<script>
$(function(){
// 从data.json中获取数据
$.ajax({
type:"get",
dataType:"json",
url:"data.json",
success:function(data){
let index = 0;
// 控制页面数据的渲染
function change(){
// 更改页面图片
$('.box img').attr('src',data[index].img_src);
// 移除已有active类的li的该属性
$('.active').removeClass('active');
// 给对应li添加active属性
$(`li:nth-child(${index+1})`).addClass('active');
}
// 点击左按钮
$('.left').click(function(){
// 前一张图
index--;
// 判断index是否小于0,即是否左边图片到头啦
if(index < 0){
index = data.length - 1
}
change();
})
// 点击右按钮
$('.right').click(function(){
// 后一张图
index++;
// 判断index是否大于等于8,即是否右边图片到头啦
if(index >= data.length){
index = 0
}
change();
})
// 实现右按钮点击事件的自动调用
let time = setInterval(function(){
// 调用右按钮的点击事件
$('.right').click()
},2000)
// 鼠标移入box
$('.box').mouseenter(function(){
// 关闭定时器
clearInterval(time)
})
// 鼠标移出box
$('.box').mouseleave(function(){
// 关闭定时器
clearInterval(time)
// 开启定时器(和上面相同的定时器)
time = setInterval(function(){
// 调用右按钮的点击事件
$('.right').click()
},2000)
})
}
})
})
</script>
</body>
</html>
data.json
[
{
"title":"1",
"img_src":"../image/lb1.jpg"
},
{
"title":"2",
"img_src":"../image/lb2.jpg"
},
{
"title":"3",
"img_src":"../image/lb3.jpg"
},
{
"title":"4",
"img_src":"../image/lb4.jpg"
},
{
"title":"5",
"img_src":"../image/lb5.jpg"
},
{
"title":"6",
"img_src":"../image/lb6.jpg"
},
{
"title":"7",
"img_src":"../image/lb7.jpg"
},
{
"title":"8",
"img_src":"../image/lb8.jpg"
}
]
注意:
由于这里是自己写的json文件,鼠标右键选择Open In Default Browser会产生本地浏览器运行项目时的跨域问题报错。
所以要选择Open with Live Server打开网页。