0;
}
this.box.ontouchmove = function (ev) {
that.fnMove(ev)
}
this.box.ontouchend = function (ev) {
that.fnEnd(ev)
}
}
};
// 轮播手指移动
Broadcast.prototype.fnMove = function (ev) {
ev.preventDefault();
changedX = ev.touches[0].clientX - startX;
var changNum = (originX + changedX);
this.box.style.cssText = "transform: translateX(" + changNum + "px);";
};
// 轮播手指抬起
Broadcast.prototype.fnEnd = function (ev) {
// 移除底部按钮样式
document.querySelector("#"+id+" .select").classList.remove("select");
basKey = 1;
setTimeout(function () {
basKey = 0;
}, 300)
if (changedX >= 100) { //向某一方向滑动
var _end = (originX + _width);
this.box.style.cssText = "transform: translateX(" + _end + "px);transition:all .3s";
_index--;
if (_index == -1) { //滑动到第一个了,为了实现无缝隙,滚到最后去
document.querySelectorAll("#"+id+" .num>li")[imgLength - 1].classList.add("select");
play(-1);
}
} else if (changedX < -100) { //向负的某一方向滑动
var _end = (originX - _width);
this.box.style.cssText = "transform: translateX(" + _end + "px);transition:all .3s";
_index++;
if (_index == imgLength) { //滑到最后一个了,为了实现无缝隙,滚到前面去
play(imgLength);
document.querySelectorAll("#"+id+" .num>li")[0].classList.add("select");
}
} else { //滑动距离太短,没吃饭不用管
this.box.style.cssText = "transform: translateX(" + originX + "px);transition:all .3s";
}
// 完成一次滑动初始化值
startX = 0;
changedX = 0;
originX = 0;
if (_index != -1 && _index != imgLength) {
document.querySelectorAll("#"+id+" .num>li")[_index].classList.add("select");
}
this.box.ontouchmove = null; //清除事件
this.box.ontouchend = null; //清除绑定事件
autoPlay = setInterval(lunbo, time) //开启轮播
}
我们定义Broadcast方法监听用户的触屏按下事件
当手指按下时,我么记录手指按下的X轴位置,单后进行监听移动和抬起的事件。
手指移动的时候我们要做到就是计算偏移量,并通过偏移量改变inner的位置。
手指抬起时,我们查看偏移量十分大于100,这个值可以改,也可以改一下变成传参。通过正负判断方向,并通过index判断当前是第几个,如果是滑动到我们复制的第一个和最后一个节点,则执行play函数,我们接下来讲解。然后改变控制点样式就比较简单了,最后初始化值,并清除监听事件。
play函数,快速滚
//首尾无缝连接
function play(index) {
setTimeout(function () {
inner.style.transition = 'all 0s';
if (index == -1) {
var _number = -imgLength * _width;
inner.style.transform = 'translateX(' + _number + 'px)';
_index = imgLength - 1;
} else if (index == imgLength) {
inner.style.transform = 'translateX(-' + _width + 'px)';
_index = 0;
}
}, 250);
}原理就是在图片滑动完成的时候,快速设置滑动变化时间设为0,并改变translateX到应该去的位置。
定时切换图片
function lunbo(){
document.querySelector("#"+id+" .select").classList.remove("select");
var tempArr = window.getComputedStyle(inner).transform.split(",");
if (tempArr.length > 2) {
originX = parseInt(tempArr[tempArr.length - 2]) 关键词:移动端轮播图完成办法(附源码)