Simple question, how would I accomplish this functionality in Jquery:
Test whether the mouse is hovering over .myBox
if ($(".myBox").mouseleave = true) {
DO SOMETHING
}开发者_如何转开发 else {something else}
OR
if ($(".myBox").mouseover = false) {
DO SOMETHING
} else {Something else}
NOTE: im looking for an IF statement
jQuery provides the is
method for checking conditions with regard to a jQuery object. In your case you can check for the :hover
CSS pseudo class:
$('.myBox').is(':hover') === true
Havre a look at this demo, try clicking the button (which will alert true
) and the tabbing to and hitting enter on the button (without the mouse, it will return false
).
DEMO: http://jsfiddle.net/marcuswhybrow/LL5JD/
Take a look at jQuery Mouse Over
$(".my_box").mouseover(function(){
// Mouse over...
});
$(".my_box").mouseout(function(){
// Mouse left...
});
Here is an example, adding a border to an image when hovering over it, and removing it after x amount of time if its not been re-hovered: See it working here
var hover_off = false;
var hover_count = 1000;
$(".my_box").mouseover(function() {
hover_off = false;
$(this).addClass('hovering');
});
$(".my_box").mouseout(function() {
hover_off = true;
setTimeout(myMouseOut, hover_count);
});
function myMouseOut() {
if (hover_off) {
$(".my_box").removeClass('hovering');
}
}
That's right, $('.myBox').is(':hover') used with jQuery 1.5.1 throws the error, but in my tests only in Opera Browser (11.01): Uncaught exception: Syntax error, unrecognized expression: hover
A workaround is using a negated expression: $('.myBox').is('not(:hover)') That worked fine while my tests in Opera 11, FF4, IE7, Chrome 5.
Use .hover() http://api.jquery.com/hover/
$(".myBox").hover(
function(){
//DO SOMETHING ON MOUSE ENTER
},
function(){
//DO SOMETHING ON MOUSE LEAVE
}
});
This did the trick for me:
var hover = false;
$('.someClass').each(function(i,e){
hover = !hover ? $(e).is(':hover') : true;
});
if (hover)
// do something
else
// do something else
use this: http://plugins.jquery.com/project/enterleave-events
$('.myBox').bind('enter leave',function() {
// do something, use $(this) to get the object
});
Act on the mouseenter
and mouseleave
events.
Or use the hover
which can handle both of them..
$('.myBox').hover(
function(e){
//do the mouseenter things here...
},
function(e){
//do the mouseleave things here...
}
);
Example at http://www.jsfiddle.net/gaby/ECYD4/
精彩评论