问题
If I have something like this:
Is there a way to fire the mouseover events on BOTH divs?
Edit: Sorry all .. I tried to simplfy the problem so it was clear to understand and I forgot to mention I have more than 100 divs like that so probably those solutions don't work. I'm going to see if I can adpat them. Many thanks everybody anyway.
回答1:
I put together a working example here with JSFiddle:
http://jsfiddle.net/gfosco/CU5YT/
It's similar to madeinstefanos answer, but specific to your example..
var mouseX = 0;
var mouseY = 0;
var front = 0;
var back = 0;
function log(text) {
$("#log").append(text + '<BR>');
}
function mouseWithin(selector) {
var pos = $(selector).position();
var top = pos.top;
var left = pos.left;
var height = $(selector).height();
var width = $(selector).width();
if (mouseX >= left && mouseY >= top && mouseX <= left + width
&& mouseY <= top + height) {
return true;
}
return false;
}
$(document).bind('mousemove', function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
if (front == 1 && !mouseWithin("#front")) {
front = 0;
log('Front Leave');
}
if (back == 1 && !mouseWithin("#back")) {
back = 0;
log('Back Leave');
}
if (front === 0 && mouseWithin("#front")) {
front = 1;
log('Front Hover');
}
if (back === 0 && mouseWithin("#back")) {
back = 1;
log('Back Hover');
}
});
回答2:
It's possible. You cannot get the mouseenter|mouseover event for a part of a element that is below another element, but if you know the dimensions and the position of the element, you can listen for mousemove event and get when the mouse enters in some particular area.
I created two divs, like yours:
<div id="aboveDiv" style="position:absolute;top:30px;left:30px;width:100px;height:100px;background-color:red;z-index:2;"></div>
<div id="belowDiv" style="position:absolute;top:80px;left:80px;width:100px;height:100px;background-color:green;z-index:1;"></div>
And I want to know when the mouse enters the area occuped by the div that is below, to do that I wrote this script:
$(function (){
var divOffset = {
top: $("#belowDiv").position().top,
left: $("#belowDiv").position().left,
right: $("#belowDiv").position().left + $("#belowDiv").width(),
bottom: $("#belowDiv").position().top + $("#belowDiv").height(),
isOver: false
}
$(window).mousemove(function (event){
if (event.pageX >= divOffset.left && event.pageX <= divOffset.right && event.pageY >= divOffset.top && event.pageY <= divOffset.bottom){
if (!divOffset.isOver){
divOffset.isOver = true;
/* handler the event */
alert("gotcha");
}
}else{
if (divOffset.isOver){
divOffset.isOver = false;
}
}
});
});
It's not simple as listen for mousenter|mouseover, but works fine.
Here a link to fiddle
来源:https://stackoverflow.com/questions/4024479/is-there-a-way-to-fire-over-events-ignoring-z-index