jquery 对同一个对象单击,双击事件处理

对同一个对象,同时监听单击事件和双击事件,利用setTimeout()对一定时间的点击事件进行逻辑处理

例如:

  

<div id="box">single-click<br>double-click</div>
<button>reset</button>

css样式:

#box {
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: lightgreen;
  margin-bottom: 20px;
}

js(引入jquery):

$(function() {

    var DELAY = 400,
          count = 0,
      timer = null;
      
    $("#box").on("click", function() {
      count++; // count clicks
    
    if (count === 1) {  // perform a single click
        timer = setTimeout(function() {
      
          $("#box").css("background-color", "red");  // can't use $(this), cus this refers to timer
        
        count = 0;  // after performed action, reset counter
      }, DELAY)
    } else {
        clearTimeout(timer); // prevent single click action
        $(this).css("background-color", "yellow");
      count = 0;
    }
  })
  .on("dblclick", function(e) {
      e.preventDefault(); // cancel default action, usual for an anchor
  });
  
  $("button").on("click", function() {
      $("#box").css("background-color", "lightgreen");
  })
})

最终效果: https://jsfiddle.net/JamesSawyer/ypw0pb4z/

 

posted @ 2016-08-08 13:05  James_Sawyer  阅读(2311)  评论(0编辑  收藏  举报