开发者

jQuery trigger event at specific mouse coordinates

开发者 https://www.devze.com 2023-01-31 10:47 出处:网络
I have a semi-transparent header and footer and I need to listen for click and hover events and trigger the same event on a different DOM element at the same mouse location.

I have a semi-transparent header and footer and I need to listen for click and hover events and trigger the same event on a different DOM element at the same mouse location.

The following snippet works great for getting the mouse coordinates, but triggering the same event with $("#container").trigger(e); does not have the desired effect.

        $("#header, #footer").click(function(e){
开发者_如何学Go          //only intercept click if it did not fall on an a tag
          if(!$(e.target).is("a")){
            e.preventDefault();
            $("#container").trigger(e); //does not work
            alert(e.pageX +', '+ e.pageY); //works
            return false;
          }
        });


After spending a lot of time in the jQuery documentation, I came up with this solution that works. @Gaby @brad thanks for the input

//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;
});


The api for trigger states that it takes a string as the parameter. You're passing it the actual event object, something like:

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

should work.

This is assuming you've already done something like:

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

ie bound the click event to the #container

0

精彩评论

暂无评论...
验证码 换一张
取 消