简体   繁体   English

mousedown 和 mouseover 上的事件侦听器有效,但在不满足条件时会被窃听并开始触发

[英]Event listener on mousedown AND mouseover works but gets bugged and starts firing when conditions are not met

I'm making an Etch-a-Sketch project and I want my grid to be filled with color on mouseover only if mousedown is true.我正在制作一个 Etch-a-Sketch 项目,我希望只有当 mousedown 为 true 时,我的网格才能在鼠标悬停时填充颜色。 My code seems to work, but if I keep drawing, it bugs and starts drawing even after mouseup.我的代码似乎可以工作,但是如果我继续绘制,它会出错并在鼠标抬起后开始绘制。 I can't figure out where the problem is in my code:我无法弄清楚问题出在我的代码中:

HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <style media="screen">

  </style>
</head>

<body>
  <div id='cont' style="height: 600px; width: 600px; display: flex; flex-wrap: wrap;">
  </div>
  <script src="script.js">

  </script>
</body>

</html>


JS:
const container = document.getElementById('cont');
const contSize = 600; //size of container in pixels
let size = 16; //number of columns and rows
let mouseDown = false;

generateGrid();

function generateGrid() {
  for (i = 0; i < (size * size); i++) {
    const createDiv = document.createElement('div');
    createDiv.style.width = contSize / size + 'px';
    createDiv.style.height = contSize / size + 'px';
    createDiv.className = 'cell';
    container.appendChild(createDiv);
  }
}

document.addEventListener('mouseover', function(e) {
  if (mouseDown) {
    if (e.target.className === 'cell') {
      e.target.style.backgroundColor = 'orange';
    }
  }
})

window.addEventListener('mousedown', () => {
  mouseDown = true;
})
window.addEventListener('mouseup', () => {
  mouseDown = false;
})

You probably need more events to set "mouseDown" to false.您可能需要更多事件来将“mouseDown”设置为 false。

Consider what happens if the user clicks and holds, moves the mouse outside, then releases.考虑如果用户点击并按住,将鼠标移到外面,然后释放会发生什么。 The mouseup won't be called, and "mouseDown" will be true even though the mouse is released. mouseup 不会被调用,即使鼠标被释放,“mouseDown”也会为true

Maybe this will help?也许这会有所帮助?

window.addEventListener("mouseout", () => {
    mouseDown = false;
}

发现问题 - 我只需要在我的页面或容器中添加样式“user-select:none”,以避免选择和拖动内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM