原理是通过 overflow: hidden; 将ul的宽带属性设置为轮播图片的个数*100%,从而这个属性来使得div中只充斥 一个li;通过js让margin-left的值改变来实现图片轮播;
*{margin:0px;border: 0}
.warp{
margin-top:100px;
margin-left: 200px;
width: 1030px;
height: 530px;
position: relative;
border: 1px solid #000000;
overflow: hidden;
box-shadow: 0 5px 54px rgb(0, 0, 0);
}
.broadcast{
margin:15px;
width: 1000px;
height: 500px;
position: relative;
overflow: hidden;
}
.broadcast ul{
width: 400%;
height: 100%;
left: 0;
top: 0;
padding: 0;
list-style: none;
}
.broadcast li{
left: 0;
float: left;
list-style: none;
}
.broadcast img{
width: 1000px;
height: 500px;
}
.broadcast ol{
position: absolute;
right: 30px;
bottom: 30px;
}
.broadcast ol li{
position: relative;
float: left;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: rgba(155, 155, 155,.45);
color: #fff;
text-align: center;
margin-right: 15px;
cursor: pointer;
line-height: 20px;
}
.broadcast ol li.first-li{
background-color:rgba(248, 248, 248, 0.45)
}
window.onload = function () {
var broadcast = document.getElementById("broadcast"),
img_list = document.getElementById("img_list"),
button_list = document.getElementById("button_list").getElementsByTagName("li"),
index = 0,
timer = null;
//初始化
if (timer) {
clearInterval(timer);
timer = null;
}
// 自动切换
timer = setInterval(autoPlay, 1000);
// 调用自动播放函数
function autoPlay() {
index++;
if (index >= button_list.length) {
index = 0;
}
imgChange(index);
}
function imgChange(buttonIndex) {
for (let i = 0; i < button_list.length; i++) {
button_list[i].className="";
}
button_list[buttonIndex].className = "first-li";//按钮样式切换
img_list.style.marginLeft = -1000 * buttonIndex + "px";
index = buttonIndex;
}
//鼠标接触div
broadcast.onmouseover = function(){
clearInterval(timer);
}
//鼠标离开div
broadcast.onmouseout = function(){
timer = setInterval(autoPlay, 2000);
}
//鼠标悬停ol
for (var i = 0; i < button_list.length; i++) {
button_list[i].id = i;
button_list[i].onmouseover = function() {
clearInterval(timer);
imgChange(this.id);
}
}
}