需要引用上文封装的动画库
代码如下:
CSS样式
* {
margin: 0;
padding: 0;
}
div {
width: 500px;
margin: 0 auto;
}
#view {
width: 500px;
margin: 0 auto;
height: 300px;
border: 5px solid black;
overflow: hidden;
position: relative;
}
#banner li {
float: left;
overflow: hidden;
}
#banner img {
width: 500px;
height: 300px;
}
#banner {
width: 2500px;
overflow: hidden
}
#prev {
float: left;
}
#next {
float: right;
}
section {
left: calc(50% - 80px);
position: absolute;
bottom: 10px;
}
span {
margin: 0 10px;
float: left;
width: 15px;
height: 15px;
background-color: blue;
}
HTML
<div id="view">
<ul id="banner">
<li><img src="../img/img/1.jpg" alt=""></li>
<li><img src="../img/img/2.jpg" alt=""></li>
<li><img src="../img/img/3.jpg" alt=""></li>
<li><img src="../img/img/4.jpg" alt=""></li>
<li><img src="../img/img/1.jpg" alt=""></li>
</ul>
<section>
<span></span>
<span></span>
<span></span>
<span></span>
<section>
</div>
<div>
<button id="prev">上一张<button>
<button id="next">下一张<button>
</div>
</head>
JS
var banner = document.getElementById('banner')
var list = document.querySelectorAll('#banner>li')
var prev = document.getElementById('prev')
var next = document.getElementById('next')
var btns = document.querySelectorAll('span')
var view = document.getElementById('view')
//计时器
var index = 0
//下一张
function nextShow() {
index++
//让点变成默认色
for (var j = 0; j < btns.length; j++) {
btns[j].style.background = 'blue'
}
//图片对应点变红色
if (index >= list.length - 1) {
//当图片最后一张是变为第一张红点
btns[0].style.backgroundColor = 'red'
} else {
btns[index].style.backgroundColor = 'red'
}
//执行动画
$_animation(banner, 'marginLeft', -500 * index, 1000, function () {
if (index >= list.length - 1) {
index = 0
banner.style.marginLeft = '0'
}
})
}
//上一张
function preShow() {//先判断后执行
index--
//让点变成默认色
for (var j = 0; j < btns.length; j++) {
btns[j].style.background = 'blue'
}
//图片对应点变红色
if (index < 0) {
//当图片最后一张是变为第一张红点
btns[list.length - 2].style.backgroundColor = 'red'
} else {
btns[index].style.backgroundColor = 'red'
}
if (index < 0) {
banner.style.marginLeft = (-500 * (list.length - 1)) + 'px'
index = list.length - 1
index--
}
//执行动画
$_animation(banner, 'marginLeft', -500 * index, 1000)
}
next.onclick = nextShow
prev.onclick = preShow
btns[0].style.background = 'red'
//按钮绑定事件
for (let i = 0; i < btns.length; i++) {
// btns[i].index=i
btns[i].onmouseenter = function () {
for (var j = 0; j < btns.length; j++) {
btns[j].style.background = 'blue'
}
//改变当前元素对象属性值
index = i
//执行动画 随着索引值变化
$_animation(banner, 'marginLeft', -500 * index, 1000)
btns[i].style.backgroundColor = 'red'
}
}
//自动轮播
var timer = setInterval(nextShow, 3000)
//当鼠标移入时,清除定时器
view.onmouseenter = function () {
clearInterval(timer)
}
//当鼠标移出时,开启定时器
view.onmouseleave = function () {
timer = setInterval(nextShow, 3000)
}