JavaScript 监听鼠标左右同时按下/同时按下移动

文章目录

  • 前言
  • 一、代码
  • 总结


前言

基于原生JavaScript, 在使用three.jsraycaster模拟瞄准及射击时用到.


一、代码

const obj = window;

let eventList = [];
let isDouble = false;
        
obj.addEventListener("mouseup", e => { mouseUp(e) });
obj.addEventListener("mousedown", e => { mouseDown(e) });
obj.addEventListener("mousemove", e => { mouseMove(e) });

obj.addEventListener("contextmenu", e => { e.preventDefault() }); // 阻止浏览器默认右键菜单

function mouseDown(e) {
  if (e.button === 1) return; // 中键
  eventList.push(e.button); // e.button 0左键 1中键 2右键
  judge();
}

function mouseUp(e) {
  if (e.button === 1) return;
  if (eventList.length === 2) isDouble = false;
  remove(e.button);
}

function mouseMove(e) {
  if(!isDouble) return;
  if(eventList[0] === 0) {
    console.log('left-right-moving');
  } else {
    console.log('right-left-moving');
  }
}
        
function remove(val) {
  if (eventList[0] == val) {
    eventList.shift();
    return;
  }
  if (eventList[1] == val) {
    eventList.pop();
    return;
  }
}

function judge() {
  if (eventList.length === 2) {
    if (eventList[0] === 0) { // 数组全等不区分元素顺序
      console.log('left-right');
    } else {
      console.log('right-left');
    }
    isDouble = true;
  }
}

总结


你可能感兴趣的:(JavaScript,javascript,前端,开发语言)