JavaScript实现轮播图效果
每天进步一点点...
使用原生JS实现基本的轮播图效果,自己可以根据需求再对应修改。
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>轮播图</title>
<link rel="stylesheet" href="./css/index.css">
<script src="./js/index.js"></script>
</head>
<body>
<div id="app">
<!-- 轮播效果一 -->
<div class="title">轮播图</div>
<div class="swiper_1" id="swiper_1">
<!-- 图片 -->
<ul class="pic_1">
<li><img src="img/1.jpg" alt=""></li>
<li><img src="img/2.jpg" alt=""></li>
<li><img src="img/3.jpg" alt=""></li>
</ul>
<!-- 导航 -->
<ol class="list_1">
<li class="current_1"></li>
<li></li>
<li></li>
</ol>
</div>
</div>
</body>
</html>
CSS样式
* {
margin: 0px;
padding: 0px;
list-style: none;
}
#app {
display: flex;
flex-flow: column;
align-items: center;
}
.title {
padding: 20px 0;
font-size: 20px;
}
/* 轮播效果一 */
.swiper_1 {
position: relative;
height: 300px;
width: 500px;
}
/* 图片 */
.swiper_1 .pic_1 {
display: flex;
overflow: hidden;
}
.swiper_1 .pic_1 li {
transition: all 0.5s;
}
.swiper_1 .pic_1 li img {
height: 300px;
width: 500px;
}
/* 导航 */
.swiper_1 .list_1 {
position: absolute;
bottom: 0px;
right: 0px;
width: 100%;
display: flex;
justify-content: center;
}
.swiper_1 .list_1 {
display: flex;
padding: 10px 0;
}
.swiper_1 .list_1 li {
transition: all 0.3s;
height: 7px;
width: 7px;
background: rgba(255, 255, 255, 0.7);
margin-right: 5px;
border-radius: 2px;
cursor: pointer;
}
.swiper_1 .list_1 .current_1 {
width: 13px;
background: rgba(255, 255, 255, 1);
}
JS代码
window.onload = function () {
let index = 0,
timer = null,
swiper_1 = document.getElementById("swiper_1"),
pic_1 = document.getElementsByClassName("pic_1")[0].children,
list_1 = document.getElementsByClassName("list_1")[0].children;
autoPlay();
timer = setInterval(autoPlay, 2000);
// 鼠标划过停止播放
swiper_1.onmouseover = function () {
clearInterval(timer);
}
// 鼠标离开继续播放
swiper_1.onmouseout = function () {
timer = setInterval(autoPlay, 2000);
}
//自动播放
function autoPlay() {
handleCurrentList()
handleCurrentPic()
}
//当前图片
function handleCurrentPic() {
pic_1[0].style.marginLeft = `-${ index*100}%`
if (index >= pic_1.length - 1) {
index = 0;
} else {
index++
}
}
//当前导航样式
function handleCurrentList() {
for (let i = 0; i < list_1.length; i++) {
//点击导航切换图片
list_1[i].onclick = function () {
index = i;
handleCurrentList()
handleCurrentPic()
}
if (i === index) {
list_1[i].classList.add("current_1")
} else {
list_1[i].classList.remove("current_1")
}
}
}
}