Home > Web Front-end > JS Tutorial > js imperfectly solves the conflict between click and dblclick events_javascript skills

js imperfectly solves the conflict between click and dblclick events_javascript skills

WBOY
Release: 2016-05-16 17:51:48
Original
1203 people have browsed it

Situation description
When an element, such as a div, is bound to both click and dblclick events, and these two events have to handle relatively independent businesses, that is, dblclick cannot be triggered when click, and dblclick cannot be triggered. trigger click. In the actual test, it was found that when dblclick, there will always be 1 click. It is this problem that will be solved below.
Situation Analysis
First of all, we need to understand the execution order of click and dblclick. The test process is abbreviated. The following are the test results:
Click: mousedown -- mouseup -- click
dblclick: mousedown -- mouseup - - click -- mousedown -- mouseup -- click -- dblclick
From this point of view, before dblclick is triggered, 2 clicks are actually executed, and the first click will be blocked (why? Well, I don’t know either).
Solution
The first thing that comes to mind is whether the event can be stopped, but I found that the browser does not provide a corresponding method. It is too difficult to implement it yourself, because the behavior associated with the click event must be made to be cancelable. That's all.
So I considered using delay, which was the only solution I could think of. Use setTimeout() to delay the completion of click event processing, and then use clearTimeout() to stop when you need to block the click.
Specific code

Copy code The code is as follows:

var test = (function() {
var clickText = 'click
';
var dblclickText = 'dblclick
';
var timer = null;
return {
click: function(){
clearTimeout(timer);
timer = setTimeout(function(){
$('body').append(clickText);
}, 300);
},
dblclick : function(){
clearTimeout(timer);
$('body').append(dblclickText);
},
init: function(){
$(function() {
$('div').click(test.click).dblclick(test.dblclick);
});
}
}
})();
test.init();

html code
Copy code The code is as follows:

click
or
dblclick


Follow-up
As mentioned in the title of the article, it is not perfect, because Under Windows, the double-click speed of the mouse can be adjusted in the control panel (not sure about other systems), so if I set the double-click speed of the system settings to be slower, the above demo will not take effect. So 300 milliseconds is just an approximation.
Author: Hu Yirui
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template