Fade out jQuery menu after delay

匆匆过客 提交于 2019-12-21 21:43:04

问题


I'm working on a jQuery drop-down menu that fades in when you hover on the top-level items. I want to set it so that when you move the mouse away the menu doesn't disappear instantly. I have this code:

$(document).ready(function(){
  $('ul#menu > li').hover(
    // mouseover
    function(){
      $(this).find('>ul').fadeIn('fast');
    },
    // mouseout
    function(){
      setTimeout( function(){
        alert('fadeout');
        $(this).find('>ul').fadeOut('fast')
        }, 1000 );
    }  
  );
});

After a second the alert happens, but the menu isn't faded out.


回答1:


window.setTimeout(), so this refers to the window object.

// mouseout
function(){
  var el=this;
  setTimeout( function(){
    alert('fadeout');
    $(el).find('>ul').fadeOut('fast')
    }, 1000 );
}  



回答2:


Have a look at hoverIntent. It'll give you greater control of the behaviour of the mouseover/mouseout events by configuration:

var config = {    
     sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
     interval: 200, // number = milliseconds for onMouseOver polling interval    
     timeout: 500, // number = milliseconds delay before onMouseOut    
};

$(document).ready(function(){
  $('ul#menu > li').hoverIntent(
    // mouseover
    function(){
      $(this).find('>ul').fadeIn('fast');
    },
    // mouseout
    function(){
       $(this).find('>ul').fadeOut('fast');
    }  
  );
});


来源:https://stackoverflow.com/questions/1457626/fade-out-jquery-menu-after-delay

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