代码之家  ›  专栏  ›  技术社区  ›  Hong Van Vit

如何在jquery中检测双击

  •  0
  • Hong Van Vit  · 技术社区  · 8 年前

    在点击事件中,如何知道这一点,需要双击。如果是点击,我希望返回;但怎么知道这是双击呢?

    <hr style="clear:both; width:100%;" />
    <p id="testClick">Click here</p>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    
    <script>
    $(document).ready(function () {
            $("#testClick").click(function () {
                //if double click: console.log("2"); and return 
                //else
                // do some thing
                console.log("1");
            });
        });
     </script>  
    2 回复  |  直到 8 年前
        1
  •  2
  •   klugjo    8 年前

    没有办法从一个单击处理程序中知道。您必须构建如下答案所示的自定义逻辑: how to detect a double on a single click in jquery

    我建议你倾听这两个事件,并围绕这一点建立你的逻辑。如果你只需要知道双击,不要听一键点击。

    使用 dblclick 事件处理程序:

    <hr style="clear:both; width:100%;" />
    <p id="testClick">Click here</p>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    
    <script>
    $(document).ready(function () {
            $("#testClick").click(function () {
                console.log("click"); // Here do nothing !
            });
            $("#testClick").dblclick(function () {
                console.log("double click");
            });
        });
     </script>
        2
  •  1
  •   Hong Van Vit    8 年前

    另一个答案基本上是正确的,但比这要复杂一点

    <hr style="clear:both; width:100%;" />
    <p id="testClick">Click here</p>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
    $(document).ready(function () {
        var isDoubleClick = false;
    
        $("#testClick").click(function () {
            setTimeout(function() {
                if(!isDoubleClick) {
                    console.log("1");
                }
            }, 500);
        });
    
        $("#testClick").dblclick(function () {
            console.log("2");
            isDoubleClick = true;
    
            setTimeout(function() {
                isDoubleClick = false;
            }, 1000);
        });
    });
    </script>

    如果出于任何原因不想使用dblclick处理程序,请使用numClicks++而不是布尔值。