JavaScript双击事件?

时间:2012-09-07 13:06:32

标签: javascript

脚本

var timer;
var firing = false;
var begen = function(id) {
    alert('one click');
};

var popupAc = function(id) {
    alert('double click');
};

function cc(id) {
    if (firing) {
        popupAc(id);
        clearTimeout(timer);
        firing = false;
        return;
    }
    firing = true;
    timer = setTimeout(function() {
        begen(id);
        clearTimeout(timer);
        firing = false;
    }, 250);
}​

HTML

<div id="myID" onclick="cc()">Click Here</div>​

示例http://jsfiddle.net/LXSZj/11/

问题:

它适用于ie和chrome,但是在firefox中,当我双击时,我得到两个警报功能。(警报双击事件和一次点击事件)

我该如何解决?

感谢。

2 个答案:

答案 0 :(得分:3)

将clearTimeout移到警报

之上
clearTimeout(timer);
popupAc(id);
PS:我可能错了,只是猜测,这里没有火狐..

答案 1 :(得分:0)

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
  var timer;
  var x = false;

  function myfun(){
    if(timer){
    clearTimeout(timer);
    alert('double click');   
    timer = 0;
     return;
    }
  timer = setTimeout(function(){
                    alert('singleclick');
                    timer=0;
                    clearTimeout(timer);                   

                },250)

            }
        </script>
        </head>
        <body>

         <p>If you singleclick/double-click on me, I will alert.</p>
            <p> i will also alert based on your click</p.

         <script>
       (function(){
     pelem = document.getElementsByTagName('p');

       for(var i=0;i<pelem.length;i++){
      pelem[i].addEventListener('click',myfun,false);
     }

   })()
  </script>

    </body>
      </html>