简体   繁体   中英

div onclick only in viewable area

here is the scenario:

<div style="position: absolute; left: 10px; top: 10px; width:50%; height: 50%; border: 1px solid #000000" onclick="alert(0)">
    <textarea style="position: absolute; left: 10px; top: 10px; width:50%; height: 50%; border: 1px solid #FF0000" ondblclick="alert(1)"></textarea>
</div>

The main problem is that the textarea's ondblclick event does not get triggered.

What happens is that if i try to doubleclick in the textarea the div onclick is triggered. I want the onclick of the div to happen ONLY if i click in the area of the div that is not covered by the textarea. How can I achieve that ?

Thanks in advance!

Try reading up on event delegation and adding handlers unobtrusively

Basically you can assign one click or dblclick handler to the div element. Within that handler you can determine the originating element and take the necessary action(s). The links should provide you with further information about that.

a basic example (using jquery and one handler function) 一个基本示例 (使用jquery和一个处理程序函数)

Just cancel the event. For traditional event attaching, you have to put return false; in the end, but I'd advice to use some more modern ways to attach event listeners (namely, addEventListener or attachEvent for IE8 and older).

You can use timers to detect intent.

Set a timer when click occurs which will get executed if no subsequent clicks occur.

On double-click clear the timer and execute your default double-click functionality.

As below,

var dblClickIntentTimer = null;

elem.click(function(){
   dblClickIntentTimer = setTimeout(function() {
      //Wait for 100 ms and then execute 'click' functionality here
   }, 100);
});


elem.dblclick(function(){
   clearTimeout(dblClickIntentTimer);

   //Do double-click functionality here  

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM