单纯的轮播图
html
js
var timer = null
var banner = document.getElementById('banner')
var dots = document.getElementById('dots')
// var arr = ['yellow', 'pink', 'green', 'skyblue'] //如果图片为纯颜色时
var arr = ['lyf1.jpg', 'lyf2.jpg', 'lyf3.jpg', 'lyf4.jpg']
arr.forEach(function (item, i) {
var li = document.createElement('li')
if (i === 0) li.classList.add('active')
dots.append(li)
// 鼠标放上时暂停
li.onmouseover = function () {
clearInterval(timer)
xbiao = i
changestyle()
}
// 鼠标放上时继续
li.onmouseout = function () {
run()
}
})
var xbiao = 0
var changestyle = function () {
// banner.style.background = arr[xbiao] //如果图片为纯颜色时
banner.style['background-image'] = `url(img/${arr[xbiao]})` // 切换图片颜色
var active = document.getElementsByClassName('active')[0]
active.classList.remove('active')
dots.children[xbiao].classList.add('active')
}
var run = function () {
timer = setInterval(function () {
if (++xbiao === arr.length) xbiao = 0
changestyle()
}, 1000)
}
run()
css
.big {
width: 1000px;
margin: 100px auto;
border: 1px solid black;
position: relative;
display: flex;
justify-content: center;
}
#banner {
width: 1000px;
height: 500px;
/* background: red; */
background: url(img/lyf1.jpg)center;
}
#dots {
width: 200px;
height: 20px;
/* background: purple; */
position: absolute;
bottom: 10px;
display: flex;
}
#dots li {
width: 20px;
height: 20px;
background: #fff;
margin: 0px 10px;
border-radius: 50%;
cursor: pointer;
}
#dots li.active {
background: #000;
}