简体   繁体   中英

jquery .hover() with else if statement

I want to put a little delay for onmouseout event for a group of sub items in a drop down menu. But I don't want to use css transitions. I set it with .hover() and setTimeout method but I wanted to put it only for a specific elements in menu - in this case just for sub items so I used if else statement for them. I have no idea why this if else statement does't work.

Here is my javascript code:

var selectors =
    {
        element: '.main-menu li:has(ul)'
    }

var opacityWorkaround = function ($element, value) {

        $element.css('opacity', value);
};

var getAnimationValues = function (visible) {
    var result = {
        visibility: visible
    };
        result.opacity = visible === 'visible' ? 1 : 0;
};

var mouseActionHandler = function ($element, visible, opacityValue) {
    $element
        .stop()
        .css("visibility", 'visible')
        .animate(getAnimationValues(visible),
        3000,
        function () {
                $(this).css("visibility", visible);
                opacityWorkaround($(this), opacityValue);
               });
};

var onMouseIn = function () {
    var $submenu = $(this).children("ul:first");
    if ($submenu) {
        mouseActionHandler($submenu, 'visible', 1);
    }
};

var onMouseOut = function () {

    var $submenu = $(this).children("ul:first");
    var $global = $('.global').children('ul');

    if ($submenu) {

               mouseActionHandler($submenu, 'hidden', 0);

    } else if ($global) {
        setTimeout(function() {
            mouseActionHandler($global, 'hidden', 0);
        },1500);
    }
};

$(selectors.element).hover(onMouseIn, onMouseOut);

I put 1500ms delay and the $global variable is referring to sub items in menu that I want to make disapear with that delay. I wanted to achieve this when user move mouse cursor out of 'some items >' tab.

Here is my fiddle example. http://jsfiddle.net/PNz9F/1/

Thanks in advance for any help!

In the example you have in your question $submenu always has a value so the else if statement is never run. You can check for a class instead.

        var timeout; 
        var $submenu = $(this).children("ul:first");
        var $global = $('.global').children('ul');

        if ($(this).hasClass('menu-item')) {

                   mouseActionHandler($submenu, 'hidden', 0);
                   mouseActionHandler($global, 'hidden', 0);
                   clearTimeout(timeout);

        } else if ($(this).hasClass('global')) {
            timeout = setTimeout(function() {
                mouseActionHandler($global, 'hidden', 0);
            },1500);
        }

您应该可以只在代码中使用:hover选择器来检查用户是否将:hover悬停在元素上并相应地运行代码

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM