只滚动一张的滑动轮播图

1、效果解释:

  无缝滚动滚动轮播图,当鼠标从第一张跳到第五张的时候,轮播图就会滚动四张,对于有些用户而言,等待时间较长,效果不是很好

    而当前的轮播图是,无论你是从第一张滑动到最后一张,或是从中间一张,滑动到第一张,都只滚动一张

2、实现思路:

    利用绝对定位,记录上次索引值,判断上次和当前索引的大小

    如果大于上次索引,则将需要滚动的图片left设置为宽度,并将上次图片慢慢滑动到-宽度的位置,之后将需要滚动的图片慢慢滑动到left为0的位置,同理可得小于的情况

3、代码 

let ul = document.querySelector('ul');
let liArr = ul.querySelectorAll('li');
let distance = liArr[0].offsetWidth;
let olArr = document.querySelector('ol').querySelectorAll('li');
let bool = true;
let lastIndex = 0;
olArr.forEach((item, index) => {
      item.index = index;
      liArr[index].style.left = distance + 'px';
      liArr[0].style.left = 0;
      item.addEventListener('click', function () {
                if (!bool) return;
                bool = false;
                olArr.forEach(item => item.classList.remove('active'));
                this.classList.add('active');
                if (lastIndex < this.index) {
                    liArr[this.index].style.left = distance + 'px';
                    startMove(liArr[lastIndex], {left: -distance})
                } else {
                    liArr[this.index].style.left = -distance + 'px';
                    startMove(liArr[lastIndex], {left: distance})
                }
                startMove(liArr[this.index], {left: 0}, function () {
                    bool = true;
                })
                lastIndex = this.index;
      })
})

备注:startMove为运动框架

猜你喜欢

转载自www.cnblogs.com/xueZ/p/11282244.html
今日推荐