-->

jQuery hover, mouseenter, mouseleave state (opacit

2019-07-15 04:18发布

问题:

I am trying to understand them but seems like I cannot. So I thought if someone can help me to better understand how these works.

When I add hover state it simply do opacity effect whether mouse is on the element or when mouse leaves element... It repeats it...

And mouseenter&leave works fine but I don't know how to tell him once $(this) so I made something and it works but perhaps someone may tell me what is correct and better way.

$("nav.topMenu-left li, nav.topMenu-right li").on('mouseenter', function() {
    $(this).animate({'opacity': '0.5'}, 100);
});

$("nav.topMenu-left li, nav.topMenu-right li").on('mouseleave', function() {
    $(this).animate({'opacity': '1'}, 100);
});

回答1:

You can combine your event handlers:

$("nav.topMenu-left li, nav.topMenu-right li").on('mouseenter mouseleave', function(e) {
   if (e.type === 'mouseenter')
      $(this).animate({'opacity': '0.5'}, 100);
   else 
      $(this).animate({'opacity': '1'}, 100);   
});

Or as you are not delegating the events you can use hover method:

$("nav.topMenu-left li, nav.topMenu-right li").hover(function(){
    $(this).animate({'opacity': '0.5'}, 100);
}, function(){
    $(this).animate({'opacity': '1'}, 100);   
})


回答2:

If you have the option, I would do this with CSS.

Example code using CSS's :hover property

CSS

div{
    width: 100px;
    height: 100px;
    background-color: blue;                
    opacity: .5;
}
div:hover{
    opacity: 1;
}

EXAMPLE

Otherwise, @undefined's solution is what you're looking for =)