在之前啊写过一篇简单的轮播的,但是在真正是业务处理中是不能用;这期博主又写了一个可以在处理业务中轮播图的,接下来让我们一起去看看吧!
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;
}
</style>
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="pre">上一张<tton>
<button id="next">下一张<tton>
</div>
接下来才是我们要说的重点:请小伙伴睁大眼睛喽!
<script>
//获取dom元素
var banner = document.getElementById('banner')
var list = document.querySelectorAll('#banner>li')
var pre = document.querySelector('#pre')
var next = document.querySelector('#next')
var btns = document.querySelectorAll('section>span')
var view=document.querySelector('#view')
var index = 0;
var flag = true
// 上一张
pre.onclick = function () {
//调用下面封装的函数并给添加点击事件
preShow()
}
//下一张
next.onclick = function () {
//调用下面封装的函数并给添加点击事件
nextShow()
}
// 初始化的颜色
btns[0].style.backgroundColor = 'red'
for (var i = 0; i < btns.length; i++) {
// 给元素绑定一属性
btns[i].i = i
// 鼠标移入事件
btns[i].onmouseenter = function () {
// 初始化颜色
for (var x = 0; x < btns.length; +x++) {
btns[x].style.backgroundColor = 'blue'
}
index = this.i
$_animation(banner, 'marginLeft', -500 * index, 1000)
btns[this.i].style.backgroundColor = 'red'
}
}
var timer=setInterval(nextShow, 2000)
view.onmouseenter=function(){
clearInterval(timer)
}
view.onmouseleave=function(){
timer=setInterval(nextShow,2000)
}
//封装的好的函数
function nextShow() {
if (flag) {
index++
// 让点变成默认色
for (var x = 0; x < btns.length; +x++) {
btns[x].style.backgroundColor = '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
}
})
}
flag = false
}
// 上一张
function preShow() {
if (flag) {
index--
for (var x = 0; x < btns.length; +x++) {
btns[x].style.backgroundColor = 'blue'
}
// 图片和点一一对应
// 执行动画
if (index < 0) {
index = list.length - 1
banner.style.marginLeft = -500 * (list.length - 1) + 'px'
index--
}
$_animation(banner, 'marginLeft', -500 * index, 1000)
if (index <0) {
btns[index-1].style.backgroundColor = 'red'
} else {
btns[index].style.backgroundColor = 'red'
}
}
flag = false
}
</script>
以上就是无缝轮播的js代码,但是博主呢有提前封装行的动画所以就省略了很多的代码。希望可以给初学者的一些帮助吧