点击绝对定位的图像不会冒泡到底层图像

Click on absolute positioned image does not bubble up to underlying image

本文关键字:图像 定位      更新时间:2023-09-26

我有一个绝对位置的图像在另一个图像的顶部。
现在,当我将点击事件绑定到背景图像并单击叠加图像时,点击事件不会像预期的那样冒泡泡到背景图像。
同时,它会进一步冒泡到底层的div。

<div class="container">
    <img src="http://dummyimage.com/600x400/000/fff&text=Background" id="bg" />
    <img src="http://dummyimage.com/100x100/ff00ff/000000&text=Overlay" id="overlay" />
</div>  

$(function(){
    $("#bg").on("click", function(){
          alert("Click on background"); 
    });   
    $("#overlay").on("click", function(){
          alert("Click on overlay - should bubble to background and container"); 
    });      
    $(".container").on("click", function(){
        alert("Click on either overlay or background which bubbled through to the container");
    });
});

jsfiddle: http://jsfiddle.net/V9dkD/2/

我真的不明白为什么会发生这种事。
如何在不改变html结构的情况下使顶部图像上的点击气泡到背景图像?

您必须触发另一个图像的点击。当涉及到鼠标事件时,重要的是结构而不是位置。

$(function(){
    $("#bg").on("click", function(){
          alert("Click on background"); 
    });   
    $("#overlay").on("click", function(){
          alert("Click on overlay - should bubble to background and container");
          $("#bg").trigger('click');
    });      
    $(".container").on("click", function(){
        alert("Click on either overlay or background which bubbled through to the container");
    });
});

这是一把有叉的小提琴。注意,这将导致.container单击事件处理程序触发两次。您可以在bg处理程序中使用return false来防止这种情况。您只需要根据您的实际用例进行一些调整。

你唯一需要改变的是#overlay的事件处理程序

$("#overlay").on("click", function(){  
    alert("Click on overlay - should bubble to background and container"); 
    $('#bg').trigger('click')
});
在js中有两个事件循环-捕获和冒泡,当它从根到通过后代到元素并返回时。事件不使用页面上的定位来传播,只有DOM结构才重要。