MouseEvent offsetX / Y返回不希望的eventListener目标的值

时间:2019-03-26 18:14:54

标签: javascript mouseevent mousemove

我有一个嵌套的布局,今天我终于能够弄清楚我的代码中的错误来自哪里。

我已经在此处找到的简化codePen中重新创建了该错误:https://codepen.io/marekKnows_com/pen/PLvqqd

将光标移到画布区域上时,您将看到一个粉红色矩形,其大小调整为一端固定在点(400,100),另一端固定在鼠标光标位置。

打开codepen控制台并查看输出消息。如果大多数情况下将光标从点400,100移开,一切正常。但是,如果将光标移到400,100点,您会注意到MouseEvent目标有时会拾取选择div,这是我的错误的根源。

发生错误时,控制台输出如下所示:

"Offset(x,y): 94,149 targetId:canvas"
"Offset(x,y): 95,149 targetId:canvas"
"Offset(x,y): -1,77 targetId:selection"
"Offset(x,y): 97,149 targetId:canvas"

如何防止mousemove监听器触发错误的目标?我只希望mousemove侦听器告诉我相对于canvas元素目标的offsetX / Y位置。

const selectionEl = document.getElementById('selection');

const canvasEl = document.getElementById('canvas');
canvasEl.addEventListener('mousemove', (ev) => {
  const msg = 'Offset(x,y): ' + ev.offsetX + ',' + ev.offsetY + ' targetId:' + ev.target.id;
  const isBad = ev.target.id === 'selection';
  if (isBad) {
    console.error(msg);
  } else {
    console.log(msg);
  }

  const topLeftX = Math.min(400, ev.clientX);
  const topLeftY = Math.min(100, ev.clientY);

  const bottomRightX = Math.max(400, ev.clientX);
  const bottomRightY = Math.max(100, ev.clientY);

  selectionEl.style.left = topLeftX + 'px';
  selectionEl.style.top = topLeftY + 'px';
  selectionEl.style.width = (bottomRightX - topLeftX) + 'px';
  selectionEl.style.height = (bottomRightY - topLeftY) + 'px';
});
* {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

#canvas {
  top: 10%;
  left: 20%;
  padding: 0px;
  width: 80%;
  height: 90%;
  border: 3px solid blue;
  position: absolute;
}

#selection {
  border: 1px solid red;
  background-color: pink;
  position: fixed;
}
<div id="canvas">
  <div id="selection"></div>
</div>

0 个答案:

没有答案