美文网首页
el-carousel 添加鼠标滑动切换效果

el-carousel 添加鼠标滑动切换效果

作者: 伊路顺峰 | 来源:发表于2023-05-28 20:02 被阅读0次

在vue2项目开发过程中用到了走马灯的组件(UI库用的ElementUI),开发过程中需求没有明确要求可以鼠标滑动切换,但是在提交测试后,测试同学提了一个问题,想要鼠标切换实现滑动效果,查看官方文档没有鼠标可以切换的事件,于是就想自己实现一个这种效果,因为我的项目是放在VR一体机里面的,所以这个是左右滑动手柄(即鼠标)切换下一张和上一张,所以判断当垂直滚动时忽略事件
主要代码:

slideBanner() {
      let that = this;
      //获取走马灯组件
      var box = document.querySelector(".el-carousel__container");
      box.addEventListener("wheel", (e) => {
        if (e.deltaY != 0) {
          //判断 如果是垂直滚动则忽略本次事件
          return;
        }
        //使用一个标识来判断当前是否正在切换轮播图,防止切换时抖动
        if (that.isMovingBanner) {
          return;
        }
        //切换时停止自动切换效果
        that.autoplay = false;

        if (e.deltaX < 0 || e.detail < 0) {
          //向左滑动
          that.isMovingBanner = true;
          that.$refs.carousel.next();
        } else {
          //向右滑动
          that.isMovingBanner = true;
          that.$refs.carousel.prev();
        }
        setTimeout(() => {
          that.isMovingBanner = false;
          that.autoplay = false;
        }, 400);
      });
    }

相关文章

网友评论

      本文标题:el-carousel 添加鼠标滑动切换效果

      本文链接:https://www.haomeiwen.com/subject/ycvdedtx.html