mousedown. propagation on siblings event.targets

雨燕双飞 提交于 2019-12-19 07:49:03

问题


I have 2 sibling-nodes with 'position absolute' which both handle mousedown event. How can I trigger the handler of 'div 1' when I am clicking on the transparent area of the 'div 2' (on the pic.)


回答1:


If the overlapping elements are dynamic, I don't believe it is possible to accomplish this using regular event bubbling since the two overlapping elements in question are "siblings".

I had the same problem and I was able to solve it with more of a hitTest scenerio where I test if the user's mouse position is within the same area.

function _isMouseOverMe(obj){
    var t = obj.offset().top;
    var o = obj.offset().left;
    var w = obj.width();
    var h = obj.height();
    if (e.pageX >= o+1 && e.pageX <= o+w){
        if (e.pageY >= t+1 && e.pageY <= t+h){
            return true;
        }
    }
    return false
}



回答2:


You'll want to use 3 event handlers, one for div1, one for div2, and one for contentArea. The contentArea handler should stop propagation so that the div2 handler is not called. The div2 handler should call the div1 handler:

function div1Click (e)
{
    // do something
}
function div2Click (e)
{
    div1Click.call(div1, e);
}
function contentAreaClick (e)
{
    e = e || window.event;
    if (e.stopPropagation) e.stopPropagation();
    e.cancelBubble = true;
    // do something
}
div1.onclick = div1Click;
div2.onclick = div2Click;
contentArea.onclick = contentAreaClick;


来源:https://stackoverflow.com/questions/7811073/mousedown-propagation-on-siblings-event-targets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!