html樣式
<div class='box'>
<ul id="imgul"> //把圖片按順序放入盒子
<li><img src="./imgs/1.jpg" alt=""></li>
<li><img src="./imgs/2.jpg" alt=""></li>
<li><img src="./imgs/3.jpg" alt=""></li>
<li><img src="./imgs/4.jpg" alt=""></li>
<li><img src="./imgs/5.jpg" alt=""></li>
</ul>
<span id="left">
< </span> <span id="right"> > //左右倆邊的小按鈕
</span>
<ol> //小按鈕
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
</div>
css樣式
* {
margin: 0;
padding: 0;
list-style: none;
} //清除默認(rèn)y樣式
.box {
position: relative;
width: 600px;
height: 370px;
margin: 50px auto;
overflow: hidden;
} //給盒子寬高,然后給圖片溢出隱藏
.box #imgul {
width: 600px;
height: 370px;
}
.box #imgul li {
width: 600px;
height: 370px;
}
.box #imgul li img {
width: 600px;
height: 370px;
display: block;
float: left;
}
.box span {
position: absolute;
top: 50%;
margin-top: -30px;
width: 30px;
height: 60px;
background-color: rgba(0, 0, 0, 0.6);
color: #fff;
font-size: 40px;
}
.box #left {
left: 0px;
}
.box #right {
right: 0px;
}
.box ol {
position: absolute;
bottom: 20px;
left: 30px;
}
.box ol li {
width: 20px;
height: 20px;
background: yellow;
font-size: 15px;
line-height: 20px;
float: left;
margin: 0px 3px;
text-align: center;
}
.box ol .active {
background: #fff;
color: red;
}
js樣式
function $(names) {
return document.getElementById(names);
}
var left = $('left'); //左按鈕
var right = $('right'); //右按鈕
var box = document.getElementsByClassName('box')[0];
var li_list = document.querySelectorAll('#imgul li'); //獲取圖片的li
var ol_list = document.querySelectorAll('ol li');
var timer = null; //聲明定時(shí)器
var count = 0;
function auto() { //執(zhí)行自動(dòng)輪播
count++;
if (count > li_list.length - 1) {
count = 0;
}
for (var i = 0; i < li_list.length; i++) {
li_list[i].style = 'display:none;';
ol_list[i].className = '';
}
li_list[count].style = 'display:block;'
ol_list[count].className = 'active';
}
timer = setInterval(auto, 500); //調(diào)用定時(shí)器
// 點(diǎn)擊右側(cè),切換下一個(gè)
right.onclick = function () {
auto();
}
// 點(diǎn)擊左側(cè),切換上一個(gè)
left.onclick = function () {
count--;
if (count < 0) {
count = li_list.length - 1;
}
console.log(count);
for (var i = 0; i < li_list.length; i++) {
li_list[i].style = 'display:none;';
ol_list[count].className = '';
}
li_list[count].style = 'display:block;';
ol_list[count].className = 'active';
}
box.onmouseover = function () { //鼠標(biāo)劃上去,停止輪播
clearInterval(timer);
}
box.onmouseout = function () { //鼠標(biāo)劃出,繼續(xù)輪播
timer = setInterval(auto, 500); //調(diào)用定時(shí)器
}
//點(diǎn)擊小按鈕,切換圖片
for (var j = 0; j < ol_list.length; j++) {
ol_list[j].ind = j; //為每個(gè)小按鈕添加下標(biāo)
ol_list[j].onclick = function () { //進(jìn)入點(diǎn)擊事件
for (var i = 0; i < li_list.length; i++) { //干掉所有人
li_list[i].style = 'display:none;';
ol_list[i].className = '';
}
li_list[this.ind].style = 'display:block;'; //留下我自己
ol_list[this.ind].className = 'active'; //留下我自己
count = this.ind; // 把當(dāng)前的角標(biāo)值賦值給count 希望他從當(dāng)前再開始
}
}