jQuery .click taking precedence over .hover
I have a print icon (image) which, when clicked, calls window.print();
. However, I also have a hover event for this same print icon, which changes the image src (gradient effect).
The code:
$( "#print_icon" ).hover(
//mouseover
function(){
$( this ).attr( "src", "http://example.com/images/image1.png" );
},
//mouseout
function(){
$( this ).attr( "src", "http://example.com/images/image2.png" );
});
// print onclick//
$( "#print_icon" ).click(function() {
windo开发者_StackOverflow社区w.print();
});
The problem:
Without clicking, the hover works as intended. When someone clicks the image, the print window appears, but the "mouseout" function doesn't run until the print window is dismissed. I'd like to change this behavior, so that the mouseout function will run even if the print window is active, or displayed.
Is this possible?
UPDATE
still doesn't work as intended:
$( "#print_icon" ).hover(
//mouseover
function(){
$( this ).attr( "src", "http://library.weill.cornell.edu/prc/images/print_icon_onclick.png" );
$( this ).click(function() {
window.print();
});
},
//mouseout
function(){
$( this ).attr( "src", "http://library.weill.cornell.edu/prc/images/print_icon.png" );
});
In all browsers I know of, window.print() launches a modal print window -- that is, a window that prevents all other interaction with the web page until it is closed. This is by design -- the browser is grabbing a snapshot of the web page as it was rendered when the print operation began.
In short, there is no way to trigger mouseout events while the print window is open.
The best alternative would be to trigger the mouseleave event in your click handler before starting the print operation:
// Click Handler
$( "#print_icon" ).click(function() {
$(this).mouseleave();
window.print();
});
You will most likely move your mouse off the button anyway to select your printer settings, so for practical purposes, this will fix the problem.
Update
setTimeout() can modify the page while the modal window is open -- at least in Firefox 5. Try this:
// Click Handler
$( "#print_icon" ).click(function() {
var that = this;
setTimeout( function() {
$(that).mouseleave();
}, 2000);
window.print();
});
Try triggering the "mouseout" event when the "click" event is executed. This way you force your printer image to change.
// Click Handler
$( "#print_icon" ).click(function() {
$(this).trigger('mouseout');
window.print();
});
I'm pretty sure there's nothing you can do about this. The print dialog blocks all interaction with the page, therefore your events will never fire while it is open.
精彩评论