将鼠标悬停在克隆项上的 jQuery

jQuery hovering a cloned item

本文关键字:jQuery 鼠标 悬停      更新时间:2023-09-26

我得到了一些这样的HTML结构:

<div id="mobileWrapper" class="ios">
    <div class="hoverWrapper">
        <div class="acvCouponPreviewWrap clearfix">
            <div class="previewLeft">
                 <span class="previewLeftInner"> 10% </span>
            </div>
            <div class="previewRight">
                 <span class="previewUser"> Some Text here </span>
            </div>
        </div>
        <!-- clone will placed here -->
    </div>
    <div class="hoverWrapper">
        <div class="acvCouponPreviewWrap clearfix">
            ...
        </div>
        <!-- clone will placed here -->
    </div>
    <div class="hoverWrapper">
        <div class="acvCouponPreviewWrap clearfix">
            ...
        </div>
        <!-- clone will placed here -->
    </div>
</div>

现在,当我悬停.hoverWrapper物品时,我想克隆悬停的物品并将其放在悬停的物品上。好的,到目前为止,这是有效的。这里的问题是悬停时闪烁的效果。一些帮助将是优雅的!

http://jsbin.com/oJeDUmU/2/edit

试过这个,但不是我想要的:

if ($(this).parent().find('.hoverWrapper')) {
    if ($(this).find('.previewActive')) {
        return false;
   }
}            

这是因为您将克隆的项目插入到.hoverWrapper 之外。当您移动鼠标的那一刻,脚本检测到您不再将鼠标悬停在它上面,因此它会删除克隆。然后它会检测到您再次悬停,因此再次插入它,然后再次检测到它,依此类推。

您所要做的就是将克隆插入包装器中。

hoveredItem.before(cloneItem);
//change to this line
hoveredItem.append(cloneItem);

http://jsbin.com/oJeDUmU/4/edit

闪烁是由以下事实引起的:只要显示克隆的项目,就会悬停在原始项目之外。然后克隆消失,你又徘徊了。

您可以通过更改代码来解决此问题,以便mouseenter原始元素但mouseleave克隆:

$(document).ready(function () {
    $("div.hoverWrapper").on('mouseenter', function () {
        console.log('enter');
        var hoveredItem = $(this);
        var position = hoveredItem.offset().top - $('#mobileWrapper').offset().top - hoveredItem.height() / 2;
        var cloneItem = $(this)
            .clone()
            .addClass('previewActive')
            .css('top', position)
            .css('left', '-34px')
            .on('mouseleave', function () {
                console.log('leave');
                $(this).fadeOut(300, function () {
                    $(this).remove();
                });
                $(this).remove();
            });
        $('#mobileWrapper').find('.previewActive').remove(); // remove other boxes
        hoveredItem.before(cloneItem);
    });
});

http://jsbin.com/oJeDUmU/16/edit