1

I've made a little experiment with Html5 canvas and Javascript events. Unfortunately, in a certain case, the javascript click event has an unexpected behavior.

This is the fiddle of the experiment : http://jsfiddle.net/Rh4kP/10/

When you click, often there is no output in the console. I observed this on Google Chrome 22.0.1 and Firefox 14.0.1

More weird, when you comment one of the "flip" line like this :

document.getElementById(hiddenCanvas).style.display = 'block';
// document.getElementById(displayedCanvas).style.display = 'none';

or

// document.getElementById(hiddenCanvas).style.display = 'block';
document.getElementById(displayedCanvas).style.display = 'none';

Click events work propertly !

4

1 回答 1

4

The definition of a click event is this, per the Mozilla Development Network:

The click event is raised when the user clicks on an element. The click event will occur after the mousedown and mouseup events. [emphasis mine]

In other words, your 'flip' event is firing so quickly modifying content that your mousedown and mouseup events are not happening on the same DOM element, and so click does not fire.

Try this example (derived from yours) to see this in action. You'll notice that when your click event fires, the mousedown and mouseup events happen on the same DOM element. But when it doesn't happen, it is because mousedown and mouseup are happening on different DOM elements. Another test to run is slowing down your flip/flop. With a very slow timeout, you'll have less of a chance of encountering this problem (though the chance still exists - I would recommend using mouseup)

Try using just the 'mouseup' event instead. I tested w/ your example and it seemed to consistently work.

See the If you delete a DOM element, do any events that started with that element continue to bubble? question for some more information.

于 2012-10-22T19:00:51.283 回答