轮播图:分为五大步(轮播图布局,左右切换,无缝轮播,自动切换,焦点切换)进行书写 ,相同的进行函数封装,调用方法,也可以用插件进行书写,这里写的是原生js轮播图。
1 轮播图布局
<!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>原生js轮播图</title>
<style>
* {
padding: 0;
margin: 0;
}
img {
display: block;
border: none;
}
.banner {
width: 600px;
height: 400px;
margin: 50px auto;
position: relative;
/* overflow: hidden; */
}
.banner .bannerWrap {
width: 2400px;
height: 400px;
position: absolute;
left: 0;
top: 0;
}
.banner .bannerWrap div {
width: 600px;
height: 400px;
float: left;
}
.banner .focusList {
position: absolute;
width: 100%;
height: 20px;
bottom: 30px;
text-align: center;
}
.banner .focusList span {
display: inline-block;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: salmon;
margin-right: 20px;
}
.banner .focusList span.active {
background-color: orangered;
}
.banner a {
display: block;
width: 41px;
height: 69px;
position: absolute;
top: 50%;
margin-top: -34.5px;
background-color: red;
background: url(./img/icon-slides.png) center no-repeat;
}
.banner a.btnLeft {
left: 0px;
background-position: 0px center;
}
.banner a.btnRight {
right: 0px;
background-position: -42px center;
}
</style>
</head>
<body>
<!-- 轮播图区域 -->
<div id="banner" class="banner">
<!-- 图片区域包裹层 -->
<div class="bannerWrap">
<div><img src="./img/" /></div>
<div><img src="./img/" /></div>
<div><img src="./img/" /></div>
<div><img src="./img/" /></div>
</div>
<!-- 焦点区域 -->
<p class="focusList">
<span class="active"></span>
<span></span>
<span></span>
<span></span>
</p>
<!-- 左右按钮 -->
<a class="btnLeft" href="javascript:;"></a>
<a class="btnRight" href="javascript:;"></a>
</div>
</body>
</html>
2 自动切换
// 获取元素
var banner = document.getElementById("banner"),
bannerWrap = banner.getElementsByClassName("bannerWrap")[0],
oDivs = bannerWrap.getElementsByTagName("div"),
oSpans = banner.getElementsByTagName("span"),
oBtns = banner.getElementsByTagName("a");
// 图片切换
// 自定义变量
var n = 0; //表示当前展示的是第几张图片 默认值0展示第一张
// 设置定时器
setInterval(function(){
// n的只自身加1