JS实现同一DOM元素上onmousedown、onclick、ondblclick事件并存解决方法(实现左键单击、双击、长按,右键点击)

<script type="text/javascript">  

  class MouseHandler {
    constructor(selector) {
      this.domBtn = document.querySelector(selector);

      // 阻止右键出菜单事件
      this.domBtn.oncontextmenu = function () {
        return false;
      };

      this.longPressTime = null;
      this.clickLock = true;
      this.clickTime = null;

      // 鼠标左右键
      this.domBtn.onmousedown = this.onMouseDown.bind(this);
      this.domBtn.onmouseup = this.onMouseUp.bind(this);

      // 鼠标单击
      this.domBtn.onclick = this.onClick.bind(this);

      // 鼠标双击
      this.domBtn.ondblclick = this.onDoubleClick.bind(this);
    }

    onMouseDown(event) {
      // 左键操作
      if (event.which === 1) {
        this.longPressTime = setTimeout(() => {
          this.clickLock = false;
          // 左键长按操作代码
          //......
          console.log("左键长按操作");
        }, 1000);
      }
      // 右键操作
      if (event.which === 3) {
        // 右键操作代码
        //......
        console.log("右键操作");
      }
    }

    onMouseUp() {
      clearTimeout(this.longPressTime);
      this.longPressTime = null;
      setTimeout(() => {
        this.clickLock = true;
      });
    }

    onClick() {
      if (this.clickTime) {
        clearTimeout(this.clickTime);
        this.clickTime = null;
      }
      if (this.clickLock) {
        this.clickTime = setTimeout(() => {
          // 单击操作代码
          //......
          console.log("单击操作");
        }, 300);
      }
    }

    onDoubleClick() {
      if (this.clickTime) {
        clearTimeout(this.clickTime);
        this.clickTime = null;
      }
      // 双击操作代码
      //......
      console.log("双击操作");
    }
  }

  // 使用
  const buttonHandler = new MouseHandler(".btn");


</script>
posted @ 2024-03-07 11:05  苏沐~  阅读(123)  评论(0编辑  收藏  举报