首页 > 解决方案 > Javascript onmousemove 和 onclick

问题描述

我想在单击鼠标并在元素上移动它时更改背景颜色,这样您就不必单击每个元素,但可以用鼠标“绘制”。但我不知道怎么做。我现在的代码就像

function change_color(x, y) {
  console.log(x, y);
  var elem = document.getElementById(x.toString() + "-" + y.toString());
  if (elem.style.backgroundColor == 'white')
    elem.style.backgroundColor = 'black';
  else
    elem.style.backgroundColor = 'white';
}
#board td {
  /*border: 1px solid rgb(175, 216, 248);*/
  width: 25px;
  height: 25px;
  border: 1px solid black;
  background-color: white;
}
<table id="board">
  <tr>
    <td id='0-0' onmousedown="change_color(0,0);"></td>
    <td id='0-1' onmousedown="change_color(0,1);"></td>
  </tr>
  <tr>
    <td id='1-0' onmousedown="change_color(1,0);"></td>
    <td id='1-1' onmousedown="change_color(1,1);"></td>
  </tr>
</table>

标签: javascripthtml-table

解决方案


您需要使用某种变量来了解鼠标是否已按下并使用 mousemove 事件。

let isDown = false
document.body.addEventListener("mousedown", function () {
  isDown = true
});

document.body.addEventListener("mouseup", function () {
  isDown = false
});

document.getElementById("grid").addEventListener("mousemove", function (evt) {
  if (isDown) evt.target.classList.add("active")
})
table {
  border-spacing: 0;
  border-collapse: collapse;
  empty-cells: show;
}

td{
  width: 10px;
  height: 10px;
  background-color: white;
  border: 1px dotted #eee;
}

td.active {
  background-color: black
}
<table id="grid">
  <tr>
    <td></td><td></td><td></td><td></td><td></td>
    <td></td><td></td><td></td><td></td><td></td>
  </tr>
  <tr>
    <td></td><td></td><td></td><td></td><td></td>
    <td></td><td></td><td></td><td></td><td></td>
  </tr>
  <tr>
    <td></td><td></td><td></td><td></td><td></td>
    <td></td><td></td><td></td><td></td><td></td>
  </tr>
  <tr>
    <td></td><td></td><td></td><td></td><td></td>
    <td></td><td></td><td></td><td></td><td></td>
  </tr>
  <tr>
    <td></td><td></td><td></td><td></td><td></td>
    <td></td><td></td><td></td><td></td><td></td>
  </tr>
</table>


推荐阅读