悬停的最佳练习

Best practive for on a hover?

本文关键字:练习 最佳 悬停      更新时间:2023-09-26

我有一个简单的函数,当你将鼠标悬停在一个元素上时,它的子元素就会出现。当用户离开(mouseout(子元素时,我将其隐藏,我还希望在用户离开(mouseout(触发器#tweeter时隐藏它。我创建了一个小提琴 http://jsfiddle.net/np1cb3k0/抱歉,如果这不是很清楚,但希望你能理解我的代码!

$('#tweeter').on('mouseenter', function(e){
    e.preventDefault();
    $(this).find('ul').show();
});
$('.subicons').mouseleave(function(){
    $(this).hide();
});

主要问题是按钮和弹出窗口之间存在分离。因此,即使ul#tweeter的孩子,由于他们没有互相拥抱,因此会触发mouseout

我建议您在鼠标输出时使用一个小的超时。鼠标悬停时清除的超时。这将允许一些时间在弹出窗口上并防止hide() .

像这样:

$('#tweeter').on({
    mouseenter : function(e){
        var $this = $(this);
        clearTimeout($this.data('_timer'));
        $(this).find('ul').show();
    },
    mouseleave : function(){
        var $this = $(this);
        $this.data('_timer', setTimeout(function(){
            $this.find('ul').hide();
        },1000))
    }
});

小提琴

在mouseLeave上,您以.subicons类而不是"#tweeter"为目标,请尝试此 http://jsfiddle.net/np1cb3k0/5/

$('#tweeter').on('mouseenter', function(e){
    //console.log('OOSH');
    e.preventDefault();
    $(this).find('ul').show();
});

$('#tweeter').mouseleave(function(){
    $(this).children('ul').hide();
});

鼠标离开事件附加到子图标。首先将鼠标悬停在子图标上后,它工作正常。