jQuery .hover() 在将鼠标悬停在新元素上后在旧元素上触发



我有一个嵌套有两个标签的div,它们是指向其他页面的链接,一个紧挨着另一个。

我正在将一张幻灯片应用于悬停时放置在标签下的第三个div。

我遇到的问题是,如果我将鼠标悬停在其中一个标签上,然后从中移除鼠标但不移动到下一个标签,效果会正常工作。

如果我直接从一个标签移动到另一个标签,隐藏div 效果的幻灯片发生在悬停的第一个标签上,而不是当前标签上。

.HTML:

<div class="top">
<label class="head left" id="home">Welcome - <?php echo $_SESSION['description'] . " (" . $_SESSION['lid'] . ")"; ?>
</label>
<label id="logout" class="head right">Logout</label>

j查询代码:

// Slide in effect for hover on class=head labels
        $("#home, #logout").hover(function () {
            // Set width to hovering element width:
            $(".labelunderscore").css("width", $(this).width() + 20);
            // Set position on labelunderscore to current element left value
            $(".labelunderscore").css("left", $(this).offset().left);
            // Check where are we hovering. Left side slide from left right from right
            if ($(this).offset().left > $(window).width()/2) {
                // We are on the right side
                $('.labelunderscore').show('slide', {direction: 'right'}, 200);
            } else {
                // Left side
                $('.labelunderscore').show('slide', {direction: 'left'}, 200);
            }
        }).mouseout(function () {
            $('.labelunderscore').hide('slide', {direction: 'left'}, 200);
        })

只需侦听标签父级上的悬停,因此它们不会被视为鼠标进出的两个独立元素:

例如

$(".top").hover(function () {

JSFiddle: http://jsfiddle.net/TrueBlueAussie/rto2hz5k/6/

找到了解决方案。问题是在页面中创建的labelunderscorediv。这"混淆"了jquery库,因为当它应用幻灯片效果时,它必须在同一div上应用滑出效果。

通过在运行时在函数中创建 labelunderscorediv 并根据悬停元素的 id 为其分配唯一 id,已对问题进行了排序。代码如下:

// Slide in effect for hover on class=head labels
        $(".head").hover(function () {
            //alert($(this).attr('id'))
            $('#main').append('<div id="labelunderscore_' + $(this).attr("id") + '" class="labelunderscore"></div>');
            // Set width to hovering element width:
            $('#labelunderscore_' + $(this).attr("id")).css("width", $(this).width() + 20);
            // Set position on labelunderscore to current element left value
            $('#labelunderscore_' + $(this).attr("id")).css("left", $(this).offset().left);
            // Check where are we hovering. Left side slide from left right from right
            if ($(this).offset().left > $(window).width()/2) {
                // We are on the right side
                $('#labelunderscore_' + $(this).attr("id")).show('slide', {direction: 'right'}, 200);
            } else {
                // Left side
                $('#labelunderscore_' + $(this).attr("id") ).show('slide', {direction: 'left'}, 200);
            }
        }, function () {
            $('#labelunderscore_' + $(this).attr("id")).hide('slide', {direction: 'left'}, 200);
        })

最新更新