悬停时的 jQuery 下拉列表行为

jQuery Dropdown behavior when hovered

本文关键字:下拉列表 jQuery 悬停      更新时间:2023-09-26

很难让这个下拉菜单正确运行。当您将鼠标悬停在下拉的元素上时,它应该保持打开状态。我做了一个函数,每半秒钟检查一次你的鼠标是否悬停在该元素上,如果是,它什么也不做,如果不是,它会关闭下拉菜单。这是我的小提琴,看看我的意思:http://jsfiddle.net/KyCyB/

这是我的JS:

$('.navBarClickOrHover').mouseover(function () {
    var targetDrop = $(this).attr('targetDropDown');
    if ($('.dropdownCont[isOpen="true"]').length != 0) {
        $('.dropdownCont[isOpen="true"]').attr('isOpen', 'false');
        $('.dropdownCont[isOpen="true"]').animate({
            "height": "0px"
        }, 200, function () {
            $('#' + targetDrop).attr('isOpen', 'false');
            $('#' + targetDrop).animate({
                "height": "200px"
            });
        });
    } else {
        $('#' + targetDrop).animate({
            "height": "200px"
        });
    }
}).mouseout(function () {
    var targetDrop = $(this).attr('targetDropDown');
    setTimeout(function () {
        if ($('#' + targetDrop).attr('isHoveredOver') == 'true') {
            //DONOTHING
        } else {
            $('#' + targetDrop).animate({
                "height": "0px"
            });
        }
    }, 500);
});
$('.dropdownCont[isOpen="true"]').mouseover(function () {
    $(this).attr('isHoveredOver', 'true');
}).mouseout(function () {
    $(this).attr('isHoveredOver', 'false');
});

我很抱歉冗长而重复的代码,一旦我让它正常工作,我就会让它更加面向对象,我只是不断弄乱它以尝试让它按照我想要的方式工作。肯定卡住了。如果您之前错过了链接,请再次显示:http://jsfiddle.net/KyCyB/任何帮助或不同的方法都会很棒!谢谢!

你可以

用css做到这一点

这是一个jsbin:http://jsbin.com/IsOFaJE/1/edit

我还制作了一个使用javascript向下/向上滑动的版本:http://jsbin.com/IsOFaJE/2/edit

这是 html:

<div>
    title
    <ul>
        <li>menuitem</li>
        <li>menuitem</li>
        <li>menuitem</li>
    </ul>
</div>

这是 css:

ul {display: none; }
div:hover ul,
ul:hover { 
    display: block; 
}

大约 30 分钟左右后,我删除了所有代码并开始了新策略,这就是我想出的,它运行良好:

$('.navBarClickOrHover').mouseenter(function(){
            var targetDropDown = $(this).attr('targetDropDown');
            $('.dropdownCont').each(function(){
                $(this).css({
                    "height":"0px"
                });
            }); 
            setTimeout(function(){
                $('#'+targetDropDown).animate({
                    "height":"200px"
                });
            },500)
        }).mouseleave(function(){
            var targetDropDown = $(this).attr('targetDropDown');
            if($("#wrapper").find("#"+targetDropDown+":hover").length == 0){
                $('.dropdownCont').each(function(){
                    $(this).animate({
                        "height":"0px"
                    });
                });
            }
            else{
                $('#'+targetDropDown).bind('mouseleave', checkIfHoveredFunc);
            }
        });
        var checkIfHoveredFunc = function(){
            $('.dropdownCont').each(function(){
                $(this).animate({
                    "height":"0px"
                });
            });
        }