要求
1.左右按钮可实现背景图向左右切换的效果
2.下方小圆点对应不一样的背景图,点击也可同样实现切换背景图效果
3.默认2s自动轮播,鼠标移入暂停轮播,移出恢复
代码
CSS
#oImg {
width: 500px;
height: 300px;
background-image: url(img/0.jpg);
background-size: 500px 300px;
position: relative;
margin: 100px auto;
transition: 1s all linear;
}
#btn-prev {
width: 30px;
position: absolute;
left: 25px;
top: 150px;
}
#btn-next {
width: 30px;
position: absolute;
left: 450px;
top: 150px;
}
ul {
position: absolute;
left: 120px;
top: 250px;
}
li {
list-style: none;
width: 10px;
height: 10px;
background-color: black;
border-radius: 50%;
margin: 10px;
float: left;
}
HTML
<div id="oImg">
<input id="btn-prev" type="button" value="<">
<input id="btn-next" type="button" value=">">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script src="02 轮播图.js"></script>
<script>
let oBox = document.querySelector("#oImg")
let oInputs = document.getElementsByTagName("input")
let oLis = document.getElementsByTagName("li")
new Banner(oBox, oInputs[0], oInputs[1], oLis)
</script>
JavaScript
class Banner {
constructor(oBox, oPrevBtn, oNextBtn, oLis) {
// index决定图片和小红点的位置,不用外界传入
this.index = 0
// 下面是需要由外界传入的
this.oBox = oBox
this.oNextBtn = oNextBtn
this.oPrevBtn = oPrevBtn
this.oLis = oLis
// 初始化背景图
this.oBox.style.backgroundImage = `url(img/${this.index}.jpg)`
// 初始化小红点
this.oLis[this.index].style.backgroundColor = `red`
// 调用事件
this.eventBind()
}
// 页面渲染函数
bgc() {
// 触发index对象,就会修改背景图
this.oBox.style.backgroundImage = `url(img/${this.index}.jpg)`
// 修改小红点,不选中时,其他变为黑色
for (let i = 0; i < this.oLis.length; i++) {
if (this.index == i) {
this.oLis[i].style.backgroundColor = `red`
} else {
this.oLis[i].style.backgroundColor = `black`
}
}
}
// 下一个按钮
next() {
this.index++
// ++会一直进行,但图片是有限个
// 设置一个限定条件
// 当index的值等于li的长度时,让它的值变为0
if (this.index == this.oLis.length) {
this.index = 0
}
this.bgc()
}
// 上一个按钮
prev() {
this.index--
// --也会一直进行,但图片是有限个
// 设置一个限定条件
// 当index的值等于-1,让它的值变为最后一个下标,即li的长度-1
if (this.index == - 1) {
this.index = this.oLis.length - 1
}
this.bgc()
}
// 小圆点按钮
clickLi() {
// 时间体内调用某种方法,指定this,反复使用
let that = this
// 将index的值改为点击的下标
// 遍历li
for (let i = 0; i < this.oLis.length; i++) {
// 点击哪个li时
this.oLis[i].onclick = function () {
// index的值等于i
that.index = i
// 点击的那一刻背景渲染
that.bgc()
}
}
}
// 定时器
// 设置两秒执行下一张图
autoplay() {
let that = this
let time = null
time = setInterval(function () {
that.next()
}, 2000);
this.oBox.onmouseover = function () {
clearInterval(time)
}
this.oBox.onmouseout = function () {
that.autoplay()
}
}
// 事件绑定
eventBind() {
let that = this
this.oNextBtn.onclick = function () {
that.next()
}
this.oPrevBtn.onclick = function () {
that.prev()
}
this.clickLi()
this.autoplay()
}
}