我有一个半透明的页眉和页脚,我需要侦听点击和悬停事件,并在同一个鼠标位置的不同DOM元素上触发相同的事件。
以下代码段非常适合获取鼠标坐标,但使用$("#container").trigger(e);
触发相同的事件却无效。
$("#header, #footer").click(function(e){ //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; } });
答案 0 :(得分:2)
在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;
});
答案 1 :(得分:1)
api for trigger表示它将字符串作为参数。你传递的是实际的event object,类似于:
$("#container").trigger(e.type);
应该有用。
这假设你已经做过类似的事情:
$("#container").bind('click', function(e){ //do something });
即将click事件绑定到#container