繁体   English   中英

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

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

我正在制作一个 Etch-a-Sketch 项目,我希望只有当 mousedown 为 true 时,我的网格才能在鼠标悬停时填充颜色。 我的代码似乎可以工作,但是如果我继续绘制,它会出错并在鼠标抬起后开始绘制。 我无法弄清楚问题出在我的代码中:

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;
})

您可能需要更多事件来将“mouseDown”设置为 false。

考虑如果用户点击并按住,将鼠标移到外面,然后释放会发生什么。 mouseup 不会被调用,即使鼠标被释放,“mouseDown”也会为true

也许这会有所帮助?

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

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

暂无
暂无

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

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