Trigger hover with jQuery?

2019-09-20 02:41发布

问题:

How do I achive this

$("#a").parent().trigger('hover')

with jQuery? The code is not working for me.

回答1:

As pointed out by TJ Crowder and Endel, this can not be done directly. However, you can achieve the effect of the span having the hover style applied to it by adding a class.

First, change your CSS so it looks like this:

#text:hover, #text.hovered
{
    /* Your styles. */
}

That means that the same styles will be applied to text when it is hovered and when it has the class hovered. Then just add the class whenever you want to have the hover affect:

$("#a").parent().addClass('hovered');

And remove it when you no longer want it:

$("#a").parent().removeClass('hovered');


回答2:

Two different answers depending on what you're really asking:

If you've hooked up a handler using hover and are trying to trigger it.

From the documentation:

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

So if you want to trigger the handler for mouseenter, trigger mouseenter. If you want to trigger the handler for mouseleave, trigger mouseleave.

Note, though, that generally it's better just to call your function directly than to call it indirectly by triggering the event.

If you're trying to trigger the CSS for an element being "hovered"

...you can't. Instead, define a class that does the same thing, and add that class to the element.



回答3:

There is no way to force a fake "hover" event in the DOM.

If you just want to change the appearance of the button, add a class to it instead.