jQuery轮播图
轮播图是制作网页时很常见的一个功能。故此发一篇关于轮播图的代码,写的不好还请见谅。
我此处使用了jQuery框架,图片切换的思路是最初在HTML标签里只放置一张图片,在切换时更改图片的路径;这样的代码会比放置图片然后切换图片的代码更加简单,优化。然后一些重复使用的代码的封装调用,更加使得代码看上去简单,清楚。
我个人觉得还是有可取之处的,当然还有很多的进步空间。欢迎大家借鉴思路。下面是我写的所有的代码。
一:HTML代码:
<body>
<div class="content">
<img src="./images/pic0.png">
<div class="prev">
<img src="./images/left1.png">
</div>
<div class="next">
<img src="./images/right1.png">
</div>
<div class="circles">
<div class="circle active">1</div>
<div class="circle">2</div>
<div class="circle">3</div>
<div class="circle">4</div>
<div class="circle">5</div>
</div>
</div>
</body>
二、css代码:
<style>
* {
padding: 0;
margin: 0;
list-style: none;
}
.content {
width: 600px;
height: 350px;
border: 2px solid pink;
position: relative;
margin: 100px;
cursor: pointer;
}
img {
width: 100%;
height: 100%;
}
.prev,
.next {
position: absolute;
display: inline-block;
top: 45%;
cursor: pointer;
}
.prev {
left: 0;
}
.next {
right: 0;
}
.circles {
width: 130px;
position: absolute;
bottom: 8px;
left: 0;
right: 0;
margin: auto;
display: flex;
justify-content: space-between;
}
.circle {
width: 20px;
height: 20px;
border-radius: 50%;
text-align: center;
background-color: rgba(0, 0, 0, 0.2);
color: #fff;
line-height: 20px;
cursor: pointer;
}
.active {
background-color: rgba(0, 0, 0, 0.7);
}
</style>
js代码
<script src="./js/jquery-3.4.1.js"></script>
<script>
// eleIndex:索引值;src:图片;timer:计时器
var eleIndex = 0, src, timer;
function imgChange() {
src = `./images/pic${eleIndex}.png`;
$('.content>img').attr('src', src);
$('.circle').eq(eleIndex).css('background-color', 'rgba(0, 0, 0, 0.7)');
}
function bgChange() {
$('.circle').eq(eleIndex).css('background-color', 'rgba(0, 0, 0, 0.2)');
}
// 上一张
$('.prev').click(function () {
bgChange();
eleIndex--;
if (eleIndex < 0) eleIndex = 4;
imgChange();
});
function func() {
bgChange();
eleIndex++;
if (eleIndex == 5) eleIndex = 0;
imgChange();
}
// 下一张
$('.next').click(func);
// 按钮
$('.circle').mouseenter(function () {
bgChange();
eleIndex = $(this).index();
imgChange();
})
timer = setInterval(func, 2000);
$('.content').hover(
function () {
clearInterval(timer);
},
function ()
timer = setInterval(func, 2000);
}
)
</script>