我无法用jquery隐藏点击事件的div

时间:2015-07-15 20:29:09

标签: javascript jquery html iframe mouseevent

我想在点击iframe时隐藏整个div元素。

$("html").on('mousemove', function(e) {
   var x = e.pageX -12;
   var y = e.pageY - 20;
   $("#test1").css({'top': y, 'left': x});
   });


$(function(){
                     $("#test1").click(function(){
                             $("#test2").hide();
                       });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1" style="width:150px;height:150px;position:relative;">
    <iframe id="test2" src="http://www.w3schools.com" style=" position:absolute;" ></iframe>
</div>

我使用了这些事件:点击,开启,鼠标,任何人似乎都有效,我想不出为什么

http://jsfiddle.net/z6tco5rg/

3 个答案:

答案 0 :(得分:1)

在你的小提琴中,无法点击div。我刚给div添加了一些填充。

<div id="test1" style="width:150px;height:150px;position:relative; padding:20px">
<iframe id="test2" src="http://www.w3schools.com" style=" position:absolute;"></iframe>
</div>

Updated fiddle

$("html").on('mousemove', function (e) {
   var x = e.pageX - 12;
   var y = e.pageY - 20;
   $("#test1").css({
       'top': y,
       'left': x
    });
});



$(function () {
    $("#test1").click(function () {
        $("#test2").hide();
    });
});

如果我理解你的问题

答案 1 :(得分:1)

您必须将Click事件处理程序代码放在iframe的范围内,因此必须是iframe中的脚本才能处理click事件。

原因是你的拖动代码使鼠标保持在iframe的范围内,因此click事件发生在不在父代的iframe内。

我能想到实现这一目标的唯一方法就是添加另一个&#34;目标&#34; div将位于iframe元素之上。然后将click事件应用于目标元素。这是通过绝对定位和z-index实现的。

不幸的是,你不能吃蛋糕而且吃得太多了:)虽然这样做可以实现目标,但需要付出代价; iframe将不再能够接受点击事件,因为目标叠加层将基本上阻止来自鼠标事件的iframe。

HTML

<div id="test1" style="width:150px;height:150px;position:relative;">
    <iframe id="test2" src="http://www.w3schools.com" style=" position:absolute; top: 0px; left: 0px;" ></iframe>
    <div id="target" style="width:304px;height:154px;position:absolute; top: 0px; left: 0px; z-index: 2; background: transparent"></div>
</div>

JS

$("html").on('mousemove', function(e) {
   var x = e.pageX -12;
   var y = e.pageY - 20;
   $("#test1").css({'top': y, 'left': x});
});


$(function(){
  $("#target").click(function(){
    $("#test2").hide();
  });
});

这是一个更新的jsfiddle: http://jsfiddle.net/z6tco5rg/15/

答案 2 :(得分:1)

如果你不需要滚动iframe,你可以在iframe上定位:绝对是一个透明的png。

<div id="test1" style="width:150px;height:150px;position:relative;">
    <img src="http://toddaustin.com/transparent.png" />
<iframe id="test2" src="http://www.w3schools.com" ></iframe>

#test1 img {
    position:absolute; 
    top:0;
    left:0;
    width:304px;
    height:150px
}

$("html").on('mousemove', function(e) {
  var x = e.pageX -12;
  var y = e.pageY - 20;
  $("#test1").css({'top': y, 'left': x});
});

$(function(){
   $("#test1 img").click(function(){
     $("#test2").hide();
   });
});

http://jsfiddle.net/aqxpo0qn/