开发者

How can I run different functions when clicking and double clicking using JavaScript?

Simply put:

  1. what I want: you click something calls function xxx(), while you double cli开发者_开发技巧ck calls another function yyy()

  2. when I put onclick and ondblclick together only xxx() executed, so how do I achieve the similar effect?

    Thanks!!


The problem is that, in some browsers, your onclick handler grabs the first click of the pair, and the ondblclick handler never sees the action. In other browsers the click is seen twice and the double click as well. The potential timing for a double click will vary by operating system, browser, and user configuration.

Handling this in a portable way is, to say the least, difficult.

I would recommend only having click handlers. But have the click handler set a variable, and a timeout. If the timeout is hit without a second click, do the onclick action. If a second click happens in that time, make sure that the timeout will do nothing and do the ondblclick action. The drawback is that this means that your double clicks won't respect the rules of the local operating system, browser, and user configuration.


Try this out:

var dbclkTimeout=-1;
somelement.onclick=function(){
  if(dbclkTimeout==-1)
    dbclkTimeout=setTimeout(function(){onclickcallback();dbclkTimeout=-1;} , 200);
  else {
    clearTimeout(dbclkTimeout);
    dbclkTimeout=-1;
    ondbclickcallback();
  }
}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜