以前从未遇到过这个问题,有人可以给我任何指示吗?
我正在创建一个网络应用程序,用于制作笔记,例如将笔记发布到白板上。目前,生成按钮将生成注释,但我想让用户可以单击 Canvas (白板)上的任意位置,并且它将在该位置生成新注释。
这是代码:-
$("#canvas").bind('click', function(e){
// Calculate offset for width, put box to the left top corner of the mouse click.
var x = e.pageX + "px";
var y = e.pageY + "px";
$("#note").clone().insertBefore("#insertAfter").attr("id", "note" + noteID).show();
$("#note" + noteID).children(".title").text("Note " + noteID);
$("#note" + noteID).css({left:x, top:y, "z-index" : zindex});
noteID++;
zindex++;
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
});
当用户单击其中一个注释时,就会出现问题,因为每次用户单击注释时,注释都会克隆到 Canvas 中,从而创建另一个注释。我想停止这种行为,并且仅在用户单击空白 Canvas 区域时创建注释。我尝试过preventDefauly、stopPropagation和stopImmediate...但它们似乎都没有任何影响。
我还尝试过其他操作,例如注释单击,但似乎无法在正确的位置获得正确的操作?还是我的处理方式完全错误?
示例如下:
http://www.kryptonite-dove.com/sandbox/animate
更新:
$('#canvas').on('click', '.note', function(e) {
e.stopPropagation();
});
这解决了笔记冒泡的问题,但现在它阻止了笔记类上的任何点击操作,我正处于未知的水域!如果您能提供有关如何使注释标题和文本的单击操作恢复正常工作的指示,我们将不胜感激:)
最佳答案
如果您想在点击 #canvas 时执行某些操作,但前提是直接点击 #canvas 而不是其子项,那么您可以使用的两个主要选项是:
根据您的更新,您可以处理每个子项的点击并阻止其传播到 #canvas,但这当然会使您可能想要为子项执行的其他处理变得复杂。
测试
event.target
property查看发起事件的 DOM 元素是否是您的 #canvas 元素。
因此,还要注意(与当前问题无关)您可以而且应该链接 jQuery 方法,而不是重新选择相同的元素:
$("#canvas").bind('click', function(e){
// if the clicked element wasn't #canvas return immediately
if (e.target != this)
return;
// Calculate offset for width, put box to the left top corner of the mouse click.
var x = e.pageX + "px";
var y = e.pageY + "px";
$("#note").clone().insertBefore("#insertAfter")
.attr("id", "note" + noteID)
.css({left:x, top:y, "z-index" : zindex})
.show()
.children(".title").text("Note " + noteID);
noteID++;
zindex++;
// You may not need any of the following any more (depending on
// what your other requirements are)
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
});
这是一个演示(带有 JS 的大幅精简版本,基本上只是此答案中的功能和您的样式): http://jsfiddle.net/H6XrW/
(请注意,您不需要同时调用 .stopImmediatePropagation()
和 .stopPropagation()
,因为前者隐式调用为您调用后者。)
关于jQuery stopPropagation()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9847152/