在网页中轮播是经常遇到大页面效果之一,在平时都是使用组件直接调用。但是其实用jq写的话企事业很简单。代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.container {
width: 700px;
position: relative;
margin: 100px auto;
align-items: center;
display: flex;
justify-content: center;
}
.container img {
width: 700px;
}
.imgs li {
display: none;
}
.imgs li:first-child {
display: block;
}
.indexes {
position: absolute;
bottom: 10px;
display: flex;
height: 20px;
}
.indexes li {
width: 15px;
height: 15px;
background: #fff;
margin: 0 10px;
}
.indexes li.active {
background: red;
}
.arrow {
height: 50px;
width: 30px;
position: absolute;
background: #000;
}
.arrow.arrowleft {
left: -50px
}
.arrow.arrowright {
right: -50px
}
</style>
</head>
<body>
<div class="container">
<div class="arrow arrowleft"></div>
<div class="arrow arrowright"></div>
<ul class="imgs">
<li>
<img src="http://p1.music.126.net/UbZ8uE01SIY-Jmo8c3fGEQ==/109951165097027317.jpg?imageView&quality=89">
</li>
<li>
<img src="http://p1.music.126.net/U4aWX25bkqj1A4bKHaeNAQ==/109951165097467733.jpg?imageView&quality=89">
</li>
<li>
<img src="http://p1.music.126.net/WDK1Xf03KHiwLEi_PWvgoQ==/109951165097312543.jpg?imageView&quality=89">
</li>
<li>
<img src="http://p1.music.126.net/w9_4EDtBaLAsg8E3k11Rkw==/109951165097376119.jpg?imageView&quality=89">
</li>
</ul>
<div class="indexes">
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
let i = 0
let timer = null
function run() {
timer = setInterval(() => {
if (++i === 4) i = 0
$('.imgs li').eq(i).show().siblings().hide()
$('.indexes li').eq(i).addClass('active').siblings('.active').removeClass('active')
}, 2000);
}
run()
$('.arrowright').click(function () {
clearInterval(timer)
if (++i > 3) i = 0
$('.imgs li').eq(i).show().siblings().hide()
$('.indexes li').eq(i).addClass('active').siblings('.active').removeClass('active')
run()
})
$('.arrowleft').click(function () {
clearInterval(timer)
if (--i < 0) i = 3
$('.imgs li').eq(i).show().siblings().hide()
$('.indexes li').eq(i).addClass('active').siblings('.active').removeClass('active')
run()
})
$('.indexes li').click(function () {
clearInterval(timer)
i = $(this).index()
$('.imgs li').eq(i).show().siblings().hide()
$('.indexes li').eq(i).addClass('active').siblings('.active').removeClass('active')
run()
})
})
</script>
</body>
</html>
相比于用js原生的写法代码量明显少了很多。