jQuery jquery分别绑定双击和单击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6330431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:42:29  来源:igfitidea点击:

Jquery bind double click and single click separately

jqueryjquery-selectors

提问by kritya

Is there something in jquery that would allow me to differentiate between behavior on double click and single click?

jquery 中有什么东西可以让我区分双击和单击的行为吗?

When I bind both to same element only the single click gets executed.

当我将两者绑定到同一个元素时,只执行一次单击。

Is there a way that wait for some time before execution of the single click to see if the user clicks again or not?

有没有办法在执行单击之前等待一段时间以查看用户是否再次单击?

Thanks :)

谢谢 :)

回答by Garland Pope

I found that John Strickler's answer did not quite do what I was expecting. Once the alert is triggered by a second click within the two-second window, every subsequent click triggers another alert until you wait two seconds before clicking again. So with John's code, a triple click acts as two double clicks where I would expect it to act like a double click followed by a single click.

我发现 John Strickler 的回答并没有完全符合我的预期。在两秒窗口内再次单击触发警报后,每次后续单击都会触发另一个警报,直到您等待两秒钟后再次单击。因此,对于 John 的代码,三次单击就像两次双击一样,我希望它像双击后单击一样。

I have reworked his solution to function in this way and to flow in a way my mind can better comprehend. I dropped the delay down from 2000 to 700 to better simulate what I would feel to be a normal sensitivity. Here's the fiddle: http://jsfiddle.net/KpCwN/4/.

我重新设计了他的解决方案,以这种方式发挥作用,并以我的思想可以更好地理解的方式流动。我将延迟从 2000 降低到 700,以更好地模拟我感觉正常的灵敏度。这是小提琴:http: //jsfiddle.net/KpCwN/4/

Thanks for the foundation, John. I hope this alternate version is useful to others.

谢谢你的基金会,约翰。我希望这个替代版本对其他人有用。

var DELAY = 700, clicks = 0, timer = null;

$(function(){

    $("a").on("click", function(e){

        clicks++;  //count clicks

        if(clicks === 1) {

            timer = setTimeout(function() {

                alert("Single Click");  //perform single-click action    
                clicks = 0;             //after action performed, reset counter

            }, DELAY);

        } else {

            clearTimeout(timer);    //prevent single-click action
            alert("Double Click");  //perform double-click action
            clicks = 0;             //after action performed, reset counter
        }

    })
    .on("dblclick", function(e){
        e.preventDefault();  //cancel system double-click event
    });

});

回答by calterras

The solution given from "Nott Responding" seems to fire both events, click and dblclick when doubleclicked. However I think it points in the right direction.

“Nott Responding”给出的解决方案似乎同时触发了双击事件,click 和 dblclick。但是我认为它指向了正确的方向。

I did a small change, this is the result :

我做了一个小改动,结果如下:

$("#clickMe").click(function (e) {
    var $this = $(this);
    if ($this.hasClass('clicked')){
        $this.removeClass('clicked'); 
        alert("Double click");
        //here is your code for double click
    }else{
        $this.addClass('clicked');
        setTimeout(function() { 
            if ($this.hasClass('clicked')){
                $this.removeClass('clicked'); 
                alert("Just one click!");
                //your code for single click              
            }
        }, 500);          
    }
});

Try it

尝试一下

http://jsfiddle.net/calterras/xmmo3esg/

http://jsfiddle.net/calterras/xmmo3esg/

回答by John Strickler

Sure, bind two handlers, one to clickand the other to dblclick. Create a variable that increments on every click. then resets after a set delay. Inside the setTimeout function you can do something...

当然,绑定两个处理程序,一个到click另一个到dblclick。创建一个每次点击都会增加的变量。然后在设置的延迟后重置。在 setTimeout 函数中,您可以执行某些操作...

var DELAY = 2000,
    clicks = 0,
    timer = null;

$('a').bind({
    click: function(e) {
        clearTimeout(timer);

        timer = setTimeout(function() {
            clicks = 0;
        }, DELAY);

        if(clicks === 1) {
            alert(clicks);
             //do something here

            clicks = 0;
        }

        //Increment clicks
        clicks++;
    },
    dblclick: function(e) {
        e.preventDefault(); //don't do anything
    }
});

回答by Mick Hansen

You could probably write your own custom implementation of click/dblclick to have it wait for an extra click. I don't see anything in the core jQuery functions that would help you achieve this.

您可能可以编写自己的 click/dblclick 自定义实现,让它等待额外的点击。我在核心 jQuery 函数中看不到任何可以帮助您实现这一目标的内容。

Quote from .dblclick()at the jQuery site

.dblclick()在 jQuery 站点引用

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

不建议将处理程序绑定到同一元素的 click 和 dblclick 事件。触发事件的顺序因浏览器而异,有些在 dblclick 之前收到两个点击事件,而其他只收到一个。双击灵敏度(被检测为双击的最大单击间隔时间)可能因操作系统和浏览器而异,并且通常是用户可配置的。

回答by IlNidoDelChiurlo

I've written a jQuery plugin that allow also to delegate the click and dblclick events

我写了一个 jQuery 插件,它也允许委托 click 和 dblclick 事件

// jQuery plugin to bind both single and double click to objects
// parameter 'delegateSelector' is optional and allow to delegate the events
// parameter 'dblclickWait' is optional default is 300
(function($) {
$.fn.multipleClicks = function(delegateSelector, clickFun, dblclickFun, dblclickWait) {
    var obj;
    if (typeof(delegateSelector)==='function' && typeof(clickFun)==='function') {
        dblclickWait = dblclickFun; dblclickFun = clickFun; clickFun = delegateSelector; delegateSelector = null; // If 'delegateSelector' is missing reorder arguments
    } else if (!(typeof(delegateSelector)==='string' && typeof(clickFun)==='function' && typeof(dblclickFun)==='function')) {
        return false;
    }
    return $(this).each(function() {
        $(this).on('click', delegateSelector, function(event) {
            var self = this;
            clicks = ($(self).data('clicks') || 0)+1;
            $(self).data('clicks', clicks);
            if (clicks == 1) {
                setTimeout(function(){
                    if ($(self).data('clicks') == 1) {
                        clickFun.call(self, event); // Single click action
                    } else {
                        dblclickFun.call(self, event); // Double click action
                    }
                    $(self).data('clicks', 0);
                }, dblclickWait || 300);
            }
        });
    });
};
})(jQuery);

回答by Muhammad Tahir

Look at the following code

看下面的代码

$("#clickMe").click(function (e) {
    var $this = $(this);
    if ($this.hasClass('clicked')){
        alert("Double click");
        //here is your code for double click
        return;
    }else{
         $this.addClass('clicked');
        //your code for single click
         setTimeout(function() { 
                 $this.removeClass('clicked'); },500);
    }//end of else
});

Demo goes here http://jsfiddle.net/cB484/

演示在这里http://jsfiddle.net/cB484/

回答by Chetan Sandeep Renu

i am implementing this simple solution , http://jsfiddle.net/533135/VHkLR/5/
html code

我正在实施这个简单的解决方案,http://jsfiddle.net/533135/VHkLR/5/
html 代码

<p>Click on this paragraph.</p>
<b> </b>

script code

脚本代码

var dbclick=false;    
$("p").click(function(){
setTimeout(function(){
if(dbclick ==false){
$("b").html("clicked")
}

},200)

}).dblclick(function(){
dbclick = true
$("b").html("dbclicked")
setTimeout(function(){
dbclick = false


},300)
});


its not much laggy


它没有太多滞后

回答by Gregory Ray

var singleClickTimer = 0; //define a var to hold timer event in parent scope
jqueryElem.click(function(e){ //using jquery click handler
    if (e.detail == 1) { //ensure this is the first click
        singleClickTimer = setTimeout(function(){ //create a timer
            alert('single'); //run your single click code
        },250); //250 or 1/4th second is about right
    }
});

jqueryElem.dblclick(function(e){ //using jquery dblclick handler
    clearTimeout(singleClickTimer); //cancel the single click
    alert('double'); //run your double click code
});

回答by Vitali Korol

This solution works for me

这个解决方案对我有用

var DELAY = 250, clicks = 0, timer = null;

$(".fc-event").click(function(e) {
    if (timer == null) {
        timer = setTimeout(function() {
           clicks = 0;
            timer = null;
            // single click code
        }, DELAY);
    }

    if(clicks === 1) {
         clearTimeout(timer);
         timer = null;
         clicks = -1;
         // double click code
    }
    clicks++;
});

回答by azzy81

I made some changes to the above answers here which still works great: http://jsfiddle.net/arondraper/R8cDR/

我在这里对上述答案进行了一些更改,但仍然很好用:http: //jsfiddle.net/arondraper/R8cDR/