问题

As above, I have a button that, when clicked, will open the sub-menu. For each option in the sub-menu there are three elements (there's actually more I think, but will keep it as 3 for simplicity). I give focus to the main div (white 'frame') of the sub-menu. Onblur of this div - I then hide the sub-menu.
This all behaves as expected - but I have the probem that when one of the 3 elements for a particular option are clicked (i.e. given focus), the main div will close due to it's onblur event handler - and the PopUp function that's linked to the onClick event of the elements for the options in the sub-menu are not fired/reached.
I need someway of only handling the onblur event of the main div in this way if the options haven't been clicked.
I have JQuery to use obviously so I'm more than happy to work with that to solve the problem.
回答1:
I'm going to post this answer - in the hope that someone can improve on it or suggest an alternative because it really does feel like a work around.
But, what I've done is on the onblur event - instead of instantly hiding the div, I've put in a small delay using a timeout so I don't alter the precedence of the onblur/onclick events fired but in effect give the onclick 'a chance' to fire.
回答2:
You can try the following idea: (Not tested so it will need some tuning/debugging..)
function mouseOverSubMenu(mouseX, mouseY) {
var divTop = $('.sub_menu').offset().top;
var divLeft = $('.sub_menu').offset().left;
var divRight = divLeft + $('.sub_menu').width();
var divBottom = divTop + $('.sub_menu').height();
return (mouseX >= divLeft &&
mouseX < divRight &&
mouseY >= divTop &&
mouseY < divBottom);
}
$('.sub_menu, .other_elements').hover(
function(e) {
if (mouseOverStartButton(e.pageX, e.pageY)) {
// show menu
}
},
function(e) {
if (!mouseOverStartButton(e.pageX, e.pageY)) {
//hide menu
}
}
);
来源:https://stackoverflow.com/questions/10755625/onblur-event-fires-before-another-divs-onclick