我有这段代码:
canvas.addEventListener("mousemove", function (e) {
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
findxy('out', e)
}, false);
canvas.addEventListener("dblclick", function (e) {
findxy('zoom', e);
}, false);
我希望当用户双击画布以防止侦听其他事件并仅执行上一个侦听器中的代码时。当事件中的代码(dblclick)完成后,我想再次收听其他事件。
答案 0 :(得分:1)
如果您想要遵循原始方法,可以使用:
https://developer.mozilla.org/de/docs/Web/API/EventTarget/removeEventListener
canvas.removeEventListener()
在你各自的逻辑中。但是,通过这种方式,您将使代码更难维护或测试。
因此,我建议采用完全不同的方法。它被称为事件委派,您只需要为整个网页收听一个事件,就可以节省相当多的资源并严格保护浏览器所需的处理能力。
我在这里解释了:
答案 1 :(得分:1)
您可以使用一个标记,告诉mouseup
,mousedown
,mouseup
,dblClick
在deactivateEvents
被解雇之前不要运行他们的代码。
下面的示例代码使用名为dblClick
的标志来告诉其他鼠标事件在dblClick
运行之前不运行其代码。
当用户触发deactivateEvents
时,将执行dblClick代码,然后清除var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// Flag: When ==true, the mouse move,down,up,out events
// will be triggered, but won't run their code.
var deactivateEvents=true;
canvas.addEventListener("mousemove", function (e) {
// only run this event's code if not deactivated
if(deactivateEvents){return;}
//
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
// only run this event's code if not deactivated
if(deactivateEvents){return;}
//
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
// only run this event's code if not deactivated
if(deactivateEvents){return;}
//
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
// only run this event's code if not deactivated
if(deactivateEvents){return;}
//
findxy('out', e)
}, false);
canvas.addEventListener("dblclick", function (e) {
findxy('zoom', e);
deactivateEvents=false;
}, false);
var $events=$('#events');
var $moves=$('#moves');
var moveCount=0;
function findxy(eType,e){
// just testing...removeable
if(eType=='move'){
moveCount++;
$moves.text(moveCount);
}else{
$events.text($events.text()+','+eType);
}
// do your findxy code
}
标志,以释放其他鼠标事件以运行其代码。
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
.inlineMe{display:inline-block;border:1px solid blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Canvas == red.<br>Mouse events code prevented until double-click in canvas.</h4>
<canvas id="canvas" width=300 height=100></canvas>
<div class='inlineMe'>
Move count: <span id='moves'>0</span>
<br><textarea id='events' rows=19></textarea>
</div>
boolean