javascript - 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>
解决方案
您需要使用某种变量来了解鼠标是否已按下并使用 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>
推荐阅读
- javascript - 当 main 字段设置为“main”而不是“browser”时,在 Electron 应用程序中访问 firestore 会导致 INTERNAL UNHANDLED ERROR
- php - 如何在where子句laravel中检查十进制值?
- sql - 在值更改时重置行号,但在分区中重复值
- xaml - 开始菜单搜索中的应用程序图标不同
- vue.js - jhipster vue npm audit fix --force 错误我不知道怎么办,请帮帮我
- python - 如何在 tkinter 中删除 { }?
- python - 当文件已经存在时,我在 watson 笔记本中收到文件未找到错误
- mysql - TypeORM 如何在 orderBy 中使用子字符串
- c++ - CMake `test_big_endian` 失败并显示`没有找到合适的类型`
- javascript - 护照javascript中特定快递路线的身份验证