开发者

Detect click outside an element (with frames)

开发者 https://www.devze.com 2023-03-27 07:26 出处:网络
I have a main page (main.html) which opens an iframe page (iframe.html).. The iframe is appended as a kind of thickbox window on main.html .Now on this iframe.html, there is a div element \"myDiv\" an

I have a main page (main.html) which opens an iframe page (iframe.html).. The iframe is appended as a kind of thickbox window on main.html .Now on this iframe.html, there is a div element "myDiv" and I need to detect click outside of this myDiv element..

The script is written inside a JS called in iframe.html

I already tried a few things (binding event to document and removing from myDiv), but that is not working..

$(document).click(function() {
  //your code here
});

$("#myDiv").unbind("click");

I am not sure开发者_JAVA百科 if this issue has got anything to do because of the iframe...

Please help me. Thank you.


Have you tried something like this? It listens for all clicks on the document, but only triggers your code if the target of the event is not the myDiv element. This way, you can tell if the click was outside the myDiv element or not.... I used jQuery:

// assign a document listener $(document).click(function(e){

if( $(e.target).attr('id') != "myDiv" )
{
  // execute your code here
  alert( e.target );        }
});

// assign an element listener
$('#myDiv').live('click',function(){alert("clicked on myDiv")});

It also allows you to assign specific code to the myDiv element to be executed if the user clicks on the myDiv element directly...


I think you want to hide the myDiv if you click outside of it, try this.

$(document).click(function() {
  $("#myDiv").hide();
});

$("#myDiv").click(function(e){
  e.stopPropagation();
});


This is a "flag & ignore" routine that I was talking about. I'm hoping there's a jQuery-native method to do this, because using flags like this is a dirty hack IMO

var myDiv = false;
$(document).click(function() {
  if (!myDiv) {
    // your code here
  }
  myDiv = false;
});

$("#myDiv").click(function(e){
  myDiv = true;
  return false; // don't know if returning false will stop propagation in jQuery
});
0

精彩评论

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