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

I can't hide a div on click event with jquery

我想在单击 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>

我已经使用了这些事件:click、on、mouseup 和任何人似乎都有效,我不明白为什么

http://jsfiddle.net/z6tco5rg/

在您的 fiddle 中无法点击 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();
    });
});

如果我正确理解你的问题

您必须将点击事件处理程序代码放在 iframe 的范围内,因此它必须是 iframe 内的一个脚本来处理点击事件。

这是因为你的拖动代码将鼠标保持在iframe的范围内,所以点击事件发生在iframe内,而不是父级内。

我认为实现此目的的唯一方法是添加另一个 "target" div,它将位于 iframe 元素之上。然后将点击事件应用于目标元素。这是通过绝对定位和 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/

如果您不需要滚动 iframe,您可以 position:absolute 在 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/