0

我正在编写一个简单的 jquery 菜单系统,该系统在鼠标悬停在文本链接上时显示/隐藏 DIV。

我想在幻灯片发生之前实现一个短暂的暂停,这样如果鼠标刚刚飞过菜单链接,菜单就不会下拉。

这就是我目前激活菜单的方式:

<script type="text/javascript"><!--
$('#aboutLink').mouseover(function() {$('#aboutMenu1').slideDown('fast');
$('#aboutLink').css("color", "#ff297b");});
 --></script>

所以实际上我需要做的是在鼠标悬停时,等待说 300 毫秒,然后,如果鼠标仍然在链接上,做动画。

4

4 回答 4

1

我建议使用 hoverIntent:http ://cherne.net/brian/resources/jquery.hoverIntent.html

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');
    }  
  );
});
于 2012-05-23T10:28:02.147 回答
1

你可能想做这样的事情:

var timeout;

$('#aboutLink').mouseover(function() {
    timeout = window.setTimeout(function() {
        $('#aboutMenu1').slideDown('fast');
        $('#aboutLink').css("color", "#ff297b");
    }, 300);
});

$('#aboutLink').mouseout(function() {
    if(timeout) {
        window.clearTimeout(timeout);
    }
});

首先你设置超时,这将在 300 毫秒后执行给定的函数,但如果用户离开 div,超时将被清除,不会发生任何事情。

于 2012-05-23T10:29:38.767 回答
0
<script type="text/javascript"><!--
var timeout;
var delay = 300;

$('#aboutLink').hover(function() {
    timeout = setTimeout(function(){
       $('#aboutMenu1').slideDown('fast');
    }, delay);
}, function(){
   if(timeout) clearTimeout(timeout);
});
$('#aboutLink').css("color", "#ff297b");});
--></script>
于 2012-05-23T10:28:18.750 回答
0

采用window.setTimeout

另外,我会推荐鼠标事件mouseleavemouseenter(参见http://api.jquery.com/mouseenter/)。省去处理嵌套元素的麻烦

然后你有

var timeoutId;

$(...).mouseleave(function (ev) { 
    if (timeoutId) { 
        window.clearTimeout(timeoutId);  
    }
    else {
        // either remove the menu or set a similar timeout for disappearance
    }
});

$(...).mouseenter(function (ev) { 
    if (timeoutId) { 
        // clear pending timeouts for other menu items
        window.clearTimeout(timeoutId); 
    }
    else {
        // either remove other menus or transition them out
    }

    timeoutId = window.setTimeout(function () {
        // show menu
    }, 300); 
});

这样做会给您留下一个简单的逻辑,因为您总是在查看当前元素。通过清除任何超时,mouseenter您不必照顾其他元素。

您当然可以乱搞,并为每个单独的菜单条目设置超时 - 为您提供更好的过渡。但是你必须管理更多的复杂性。

于 2012-05-23T10:34:58.490 回答