代码
//封装获取id函数
function $(id) {
return document.getElementById(id);
}
var banner = $('banner');
var ul = banner.getElementsByTagName('ul')[0];
var imgs = ul.getElementsByTagName('li');
var xiaBiao = document.querySelectorAll('.square>ul>li')
//克隆第一个和最后一个
ul.appendChild(imgs[0].cloneNode(true));
ul.insertBefore(imgs[imgs.length - 2].cloneNode(true), imgs[0]);
var rBtn = $("rbtn"),
lBtn = $("lbtn");
//获取图片的宽度值
var imgw = imgs[0].offsetWidth;
//var imgw = parseInt(window.getComputedStyle(imgs[0], null).width);
//重置ul的宽度
ul.style.width = imgs.length * imgw + 'px';
ul.style.left = -imgw + 'px';
//设置下标初始值
var idx = 1;
rBtn.onclick = function() {
// if (timer) return;
if (idx >= imgs.length - 1) {
idx = 1;
ul.style.left = -imgw * idx + 'px';
}
//下个图片的下标
idx++;
move()
//重置ul的宽度
//ul.style.left = -imgw * idx + 'px';
}
lBtn.onclick = function() {
// if (timer) return;
if (idx <= 0) {
idx = imgs.length - 2;
ul.style.left = -imgw * idx + 'px';
}
//下个图片的下标
idx--;
move()
//重置ul的宽度
// ul.style.left = -imgw * idx + 'px';
}
var times = null;
//自动播放
times = setInterval(function() {
rBtn.onclick()
}, 2000)
//鼠标划过暂停自动播放
banner.onmouseover = function() {
clearInterval(times);
}
//鼠标划出开启自动播放
banner.onmouseout = function() {
times = setInterval(function() {
rBtn.onclick()
}, 2000)
}
// 点击下标对应的图片
for (var i = 0; i < xiaBiao.length; i++) {
(function(k) {
xiaBiao[k].onclick = function() {
idx = k + 1;
move();
}
})(i)
}
var timer = null;
//移动一个图片距离
function move() {
timer = setInterval(function() {
mubiao = idx * imgw;
curr = -parseInt(ul.style.left);
shengyu = mubiao > curr;
shengyuTwo = mubiao - curr
step = Math.ceil(Math.abs(shengyuTwo) / 20)
if (shengyu) {
curr += step;
} else {
curr -= step;
}
if (shengyu ? mubiao <= curr : curr <= mubiao) {
clearInterval(timer)
}
ul.style.left = -curr + 'px'
}, 17)
//小白条随下标移动
for (var i = 0; i < xiaBiao.length; i++) {
xiaBiao[i].className = "";
}
xiaBiao[(idx - 1) % 3].className = 'active'
}
网友评论