我正在编写一小段简单的代码,用于在鼠标位于框中的任何位置绘制像素。我也想有一个清晰的按钮。绘图可以正常工作,但我似乎不能让清除按钮工作。下面是我的.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新手,所以我不知道。
发布于 2011-05-28 05:28:51
将您的函数重命名为其他名称(不是clear())。
function removePixels() {
var box = document.getElementById("box");
if (box.hasChildNodes() )
{
while ( box.childNodes.length >= 1 )
{
box.removeChild( box.firstChild );
}
}
}//end function发布于 2011-05-28 05:27:58
我不认为clear是一个有效的函数名称。
http://jsfiddle.net/zUJ2e/
编辑:是的,绝对不是
http://www.roseindia.net/javascript/javascript-clear-method.shtml
发布于 2011-05-28 05:16:26
你不应该在NodeList上使用“for...in”循环:
for (var n = 0; n < childNodes.length; ++n)
box.removeChild(childNodes[n]);NodeList不是数组,尽管有时它的行为有点像数组。通常,“for...in”用于对象,而不是数组。
另一个完全不同的注意事项:你可能会在一些浏览器上遇到这样的“样式”设置问题(对于你的“像素”)。在所有浏览器中,DOM节点的"style“属性都被视为奇特的魔术,但我的记忆是,做您正在做的事情可能并不总是有效。相反,您需要设置someElement.style的各个属性。
https://stackoverflow.com/questions/6157699
复制相似问题