【发布时间】:2010-12-18 22:09:07
【问题描述】:
我有一个半透明的页眉和页脚,我需要监听单击和悬停事件,并在同一鼠标位置的不同 DOM 元素上触发相同的事件。
下面的sn-p非常适合获取鼠标坐标,但是用$("#container").trigger(e);触发同样的事件并没有想要的效果。
【问题讨论】:
-
您是否将
click处理程序附加到#container元素?
我有一个半透明的页眉和页脚,我需要监听单击和悬停事件,并在同一鼠标位置的不同 DOM 元素上触发相同的事件。
下面的sn-p非常适合获取鼠标坐标,但是用$("#container").trigger(e);触发同样的事件并没有想要的效果。
【问题讨论】:
click 处理程序附加到#container 元素?
在 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;
});
【讨论】:
api for trigger 声明它将字符串作为参数。你传递给它的是实际的event object,类似于:
$("#container").trigger(e.type);
应该可以。
这是假设你已经做了类似的事情:
$("#container").bind('click', function(e){ //do something });
即绑定点击事件到#container
【讨论】:
#container 上有一个处理程序吗?