jQuery hover, mouseenter, mouseleave state (opacity animate)

。_饼干妹妹 提交于 2019-12-24 04:48:08

问题


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 =)



来源:https://stackoverflow.com/questions/12727561/jquery-hover-mouseenter-mouseleave-state-opacity-animate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!