我正在编写一段简单的代码来在鼠标位于框中的任何位置绘制像素。我也想要一个清除按钮。绘图工作正常,但我似乎无法让清除按钮工作。以下是我的 .js 文件的相关部分:
function pixel(x, y) {
var pix = document.createElement("div");
pix.setAttribute("style", "position:absolute;left:" + x + "px;top:" +
y + "px;width:3px;height:3px;background:#000;cursor:crosshair");
return pix;
}
var mouseDown = false;
function draw(event) {
if (!mouseDown) return;
var x = event.clientX;
var y = event.clientY;
document.getElementById("box").appendChild(pixel(x, y));
}
/* Neither 1, 2, nor 3 work! */
function clear() {
var box = document.getElementById("box");
/* 1 */
// box.innerHTML = "";
/* 2 */
// box.childNodes = new NodeList();
/* 3 */
for (n in box.childNodes)
box.removeChild(n);
}
我的 HTML 文件的相关部分是:
<body onmousedown="mouseDown=true" onmouseup="mouseDown=false">
<div id="box" onmouseover="document.getElementById('box').style.cursor='crosshair'"
onmousemove="draw(event)"></div>
<button onclick="clear()">Clear</button>
</body>
该框也使用 CSS 进行了一些格式化,但这应该不是问题。我觉得问题可能是我正在从框中删除像素,而不是从文档或其他内容中删除像素,但我是 JavaScript 菜鸟,所以我不知道。