3

我正在编写一段简单的代码来在鼠标位于框中的任何位置绘制像素。我也想要一个清除按钮。绘图工作正常,但我似乎无法让清除按钮工作。以下是我的 .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 菜鸟,所以我不知道。

4

4 回答 4

2

将您的函数重命名为其他名称(不明确())。

function removePixels() {
var box = document.getElementById("box");

if (box.hasChildNodes() )
{
while ( box.childNodes.length >= 1 )
{
    box.removeChild( box.firstChild );       
} 
}

  }//end function
于 2011-05-27T21:28:51.160 回答
1

我认为这不是clear函数的有效名称。

http://jsfiddle.net/zUJ2e/

编辑:是的,绝对不是

http://www.roseindia.net/javascript/javascript-clear-method.shtml

于 2011-05-27T21:27:57.620 回答
0

您将按钮连接到事件处理程序的方式是无意中点击 document.clear(),而不是您定义的 clear() 函数。

避免这种情况的一种方法是将函数重命名为其他名称。例如,如果将函数重命名为 myClear(),则应该可以解决这个特定的冲突。然而,这确实感觉有点狡猾。

您可以在 JavaScript 本身中绑定您的事件处理程序,这似乎更可靠。如果您使用的是 JQuery 库,则可以执行以下操作,例如:

// when the document is ready...
$(document).ready(function() {
    // connect all buttons to the clear event handler.
    $('button').click(clear); 
})

如果你想坚持使用 vanilla JavaScript,你可以在 DOM 树基本准备就绪时在 JavaScript 中设置 onclick 属性。

<body onmousedown="mouseDown=true" onmouseup="mouseDown=false">
<div id="box" onmouseover="document.getElementById('box').style.cursor='crosshair'"
     onmousemove="draw(event)"></div>
<!-- button has an id to make it selectable with getElementById() -->
<button id="button">Clear</button>

<!-- Placed at the bottom so we have a chance of getting button -->
<script>
    document.getElementById("button").onclick = clear;
</script>

</body>
于 2011-05-27T21:45:06.177 回答
0

您不应该在 NodeList 上使用“for ... in”循环:

for (var n = 0; n < childNodes.length; ++n)
  box.removeChild(childNodes[n]);

NodeList 不是一个数组,尽管它有时有点像一个数组。一般来说,“for ... in”是针对对象,而不是数组。

另一个完全独立的注释:您可能会在某些设置“样式”的浏览器上遇到问题(对于您的“像素”)。DOM 节点的“样式”属性在所有浏览器中都被视为一种奇怪的魔法,但我记得做你正在做的事情可能并不总是有效。相反,您将设置someElement.style.

于 2011-05-27T21:16:25.683 回答