【问题标题】:jQuery trigger event at specific mouse coordinates特定鼠标坐标处的 jQuery 触发事件
【发布时间】:2010-12-18 22:09:07
【问题描述】:

我有一个半透明的页眉和页脚,我需要监听单击和悬停事件,并在同一鼠标位置的不同 DOM 元素上触发相同的事件。

下面的sn-p非常适合获取鼠标坐标,但是用$("#container").trigger(e);触发同样的事件并没有想要的效果。

$("#header, #footer").click(function(e){ //如果点击没有落在a标签上,则只拦截点击 if(!$(e.target).is("a")){ e.preventDefault(); $("#container").trigger(e); //不起作用 警报(e.pageX +','+ e.pageY); //作品 返回假; } });

【问题讨论】:

  • 您是否将click 处理程序附加到#container 元素?

标签: jquery html css


【解决方案1】:

在 jQuery 文档中花费了大量时间后,我想出了这个可行的解决方案。 @Gaby @brad 感谢您的意见

//listen for clicks and mousemovement in the header/footer
//and pass event through to the content div where applicable
$("#header, #footer").bind("click mousemove", function(e){  
    //only intercept event if it did not fall on an "a" tag 
    //within header/footer
    if(!$(e.target).is("a")){
        e.preventDefault();
        $("#container").trigger(e);
        return false;
    }
});

$("#container").bind("click mousemove", function(e){  
    e.preventDefault();  
    //get the coordinates of all "a" decendents of #container  
    $(this).find("a").each(function(){   
        var pos = $(this).offset();  
        var height = $(this).height();
        var width = $(this).width();
        //determine if this event happened
        //within the bounds of this "a" element
        if((e.pageX >= pos.left && e.pageX <= (pos.left + width))
           && (e.pageY >= pos.top && e.pageY <= (pos.top + height))){
            //if event type is mousemove, trigger hover
            if(e.type == "mousemove"){
                $(this).css("text-decoration", "underline");
                //else, pass trigger on to element as is (click)
            } else {
                window.location = $(this).attr("href");
            } 
        }
    });
    //prevent bubbling
    return false;
});

【讨论】:

    【解决方案2】:

    api for trigger 声明它将字符串作为参数。你传递给它的是实际的event object,类似于:

    $("#container").trigger(e.type);
    

    应该可以。

    这是假设你已经做了类似的事情:

    $("#container").bind('click', function(e){ //do something });
    

    即绑定点击事件到#container

    【讨论】:

    • @brad 这行得通,但我失去了 e.pageX 和 e.pageY 鼠标坐标,所以我不知道他们想点击#container 上的哪个位置。
    • 啊抱歉,没有注意到你有这个要求...好问题我得考虑一下。
    • @brad,传递事件可以正常工作(自 v1.3)。查看api.jquery.com/trigger 的文档(第二个构造函数
    • @brad, @Roxtonic 它应该可以工作,因为这个例子证明了jsfiddle.net/gaby/3F38g 你确定#container 上有一个处理程序吗?
    • @roxtonic,为此,您要接收事件的元素必须是您手动触发事件的元素的父元素。这就是冒泡事件的工作原理quirksmode.org/js/events_order.html。您需要使用事件顺序的捕获阶段来执行此操作,但 jquery 目前不支持(v1.5 中预期)。它现在的工作方式是,你在某事上触发一个事件,然后在 DOM 层次结构中冒泡。
    猜你喜欢
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多