顶级/下级菜单上的隐藏()延迟问题,但当鼠标再次进入时取消隐藏()

Problems with hide() delay on top/sub level menu BUT cancel hide() when mouse enters again

本文关键字:隐藏 鼠标 取消 延迟 菜单 问题 顶级      更新时间:2023-12-09

我的菜单出现onmouseout/over延迟问题。我发现,通过将setTimeout数字从100改为2000,它会将顶级菜单从隐藏延迟到下级菜单,并且在新的onmouseover上,它们仍然隐藏,以下是我试图实现的:

在主菜单或主菜单和辅助菜单的onmouseout上,延迟隐藏2-3秒,但如果用户返回时将onmouseover任一元素,则会取消延迟并继续显示。

我在网上找到的大多数帮助只是为了隐藏延迟,而不是在新的onmouseover上取消它。

这是我的代码:http://jsfiddle.net/MQ2cg/4/

jQuery.fn.hoverWithDelay = function (inCallback, outCallback, delay) {
    this.each(function (i, el) {
        var timer;
        $(this).hover(function () {
            timer = setTimeout(function () {
                timer = null;
                inCallback.call(el);
            }, delay);
        }, function () {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            } else outCallback.call(el);
        });
    });
};
$(document).ready(function () {
    var hovering = {
        mainMenu: false,
        categories: false
    };
    function closeSubMenus() {
        $('ul.sub-level').css('display', 'none');
    }
    closeSubMenus();
    function closeMenuIfOut() {
        setTimeout(function () {
            if (!hovering.mainMenu && !hovering.categories) {
                $('#navigation').fadeOut('fast', closeSubMenus);
            }
        }, 100);
    }
    $('ul.top-level li').hover(function () {
        $(this).find('ul').show();
    }, function () {
        $(this).find('ul').hide();
        closeMenuIfOut();
    }, 100);
    $('#categories').hoverWithDelay(function () {
        $('#navigation').show();
        hovering.categories = true;
    },
    function () {
        hovering.categories = false;
        closeMenuIfOut();
    }, 175);
    $('#navigation').hover(function () {
        hovering.mainMenu = true;
    }, function () {
        hovering.mainMenu = false;
    });
    $('#categories').click(function () {
        window.location.href = $('a', this).attr('href');
    });
});

谢谢你的帮助。

这些问题似乎很相似:

JS鼠标悬停图像上传按钮(如Facebook)

正如Amin Eshaq所指出的,使用mouseenter/mouseeve

这是工作代码:

    $(this).bind({
            'mouseenter' : function () {
                    timer = setTimeout(function () {
                            timer = null;
                            inCallback.call(el);
                    }, delay);
            },
            'mouseleave' : function () {
                    if (timer) {
                            clearTimeout(timer);
                            timer = null;
                    } else outCallback.call(el);
            }            
    });