I have a link. It hov开发者_Python百科er has some background effects.
I want to fire this hover through jquery.
You can fire the javascript hover (mouseover
of mouseenter
or mousemove
or something, depending on the js lib), but you can't fire the CSS :hover state with Javascript.
You can only use jQuery to fire the event IF jQuery was used to attach the event.
Use JQuery hover() wrapped in document.ready
, so that it automatically fires up when a hover happens over the link
$(document).ready(function() {
$("#YourLinkId").hover(functionToHandleWhenMouseEnters,
functionToHandleWhenMouseLeaves);
});
function functionToHandleWhenMouseEnters() {
$(this).css({background : red});
}
function functionToHandleWhenMouseLeaves() {
$(this).css({background: white});
}
Edit:
I am note very sure if this is what you wanted, but as per David's comment, it might not be it. If you want to programatically fire (trigger) a hover, then you should use jQuery trigger()
$("#YourLinkId").trigger("mouseover");
I'm not sure, but I don't believe you can fire the :hover
state for a CSS element. I would suggest you handle the hover events for the element and add/remove a special class for your element, for example:
CSS:
#myElement.myClass { }
jQuery:
$("#myElement").hover(
function(){
//mouse in
$(this).addClass("myClass");
}, function(){
$(this).removeClass("myClass");
});
$('#hrefID').trigger('mouseover'); //triggers hover
//your 'hover' code runs....
$('#hrefID').trigger('mouseout'); //removes hover
//your 'mouse out' portion of hover code runs here...
see this link on jQuery Trigger()
精彩评论