Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - How to detect click event in iframe using jquery

This is my iframe:

#htmlDiv {
    position: absolute;
    top: 0px;
    left: 300px;
    height: 650px;
    width: 1130px;
}

#htmlFrame {
    position: absolute;
    top: 0px;
    left: 0px;
    margin: 10px 10px 10px 10px;
    padding: 0px 0px 0px 0px;
    height: 630px;
    width: 1110px;
}

<div id="htmlDiv">
    <iframe id="htmlFrame"></iframe>
</div>

$('#htmlFrame').click(function(){
    alert('clicked');
});

But when I click inside the iframe, it doesn't show "clicked".
How do I detect click inside iframe.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot detect a click event on an iframe. What can be done is you can place a overlapping layer on top of your iframe and capture the click event of the overlapping div. See below snippet:

$("#overlap").on("click",function(){
alert("click");
$("#overlap").css("z-index",-1);

});
$("#htmlFrame").on("mouseleave",function(){
$("#overlap").css("z-index",1);
});
#htmlDiv {
    position: absolute;
    top: 0px;
    left: 300px;
    height: 65px;
    width: 113px;
}

#htmlFrame {
    position: absolute;
    top: 0px;
    left: 0px;
    margin: 10px 10px 10px 10px;
    padding: 0px 0px 0px 0px;
    height: 63px;
    width: 110px;
}

#overlap{
  position: absolute;
  background-color:trasparent;
  top: 0px;
  left: 0px;
  margin: 10px 10px 10px 10px;
  padding: 0px 0px 0px 0px;
  width: 110px;
  height:63px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="htmlDiv">
    <iframe id="htmlFrame"></iframe>
  <div id="overlap">
</div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...