Home Article Practice 简易的banner图(js)

简易的banner图(js)

2022-11-20 20:28  views:496  source:mjy9063    

window.addEventListener('load', function() {
var arrow_l = document.querySelector(".arrow-l");
var arrow_r = document.querySelector(".arrow-r");
var box = document.querySelector(".banner-container");
//得到轮播图盒子的宽
var boxWidth=box.offsetWidth;
//当鼠标经过轮播图时左右箭头显示,离开时箭头隐藏
box.addEventListener("mouseenter", function() {
arrow_l.style.display = "block";
arrow_r.style.display = "block";
clearInterval(timer);
timer = null;
})
box.addEventListener("mouseleave", function() {
arrow_l.style.display = "none";
arrow_r.style.display = "none";
timer = setInterval(function() {
// 手动调用点击事件
arrow_r.click();
}, 2000)
})
// 动态生成小圆圈
var ul = box.querySelector("ul");
var ol = box.querySelector(".circle");
for(var i = 0; i < ul.children.length; i++) {
// 创建li
var li = document.createElement("li");
li.setAttribute("index", i);
// 记录当前小圆圈索引号通过自定义属性
ol.appendChild(li);
li.addEventListener("click", function() {
for(var i = 0; i < ol.children.length; i++) {
ol.children[i].className = "";
}
this.className = "current";
// 点击小圆圈移动图片
// 得到当前点击的这个li的index的属性
var index = this.getAttribute("index");
// 点击哪个li就把index给num和circle
num = index;
circle = index;
animate(ul, -index * boxWidth);
})
}
ol.children[0].className = "current";
// 复制ul的第一个li,来做第一章图片滑动效果
var first = ul.children[0].cloneNode(true);
ul.appendChild(first);
var num = 0;
var circle = 0;
// 右箭头点击事件
arrow_r.addEventListener("click", function() {
// 如果走到了最后复制的一张图片,此时快速跳转left=0
// ul.children.length-1
if(num == ul.children.length-1) {
ul.style.left = 0;
num = 0;
}
num++;
animate(ul, -num * boxWidth);
circle++;
if(circle == ol.children.length) {
circle = 0;
}
circleChange();
})
arrow_l.addEventListener("click", function() {
// 如果走到了最前面一张图片,此时快速跳转轮播图的最后一张
if(num == 0) {
num = 4;
ul.style.left = -(ul.children.length-1) * boxWidth + 'px';
}
num--;
animate(ul, -num * boxWidth);
circle--;
if(circle < 0) {
circle = ol.children.length-1;
}
circleChange();
})
function circleChange() {
for (var i= 0; i < ol.children.length; i++) {
ol.children[i].className="";
}
ol.children[circle].className="current";
}
// 定时器,鼠标离开时自动播放
var timer = setInterval(function() {
arrow_r.click();
}, 3000)
})



Disclaimer: The above articles are added by users themselves and are only for typing and communication purposes. They do not represent the views of this website, and this website does not assume any legal responsibility. This statement is hereby made! If there is any infringement of your rights, please contact us promptly to delete it.

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)