如何在on("mouseenter") 2秒后延迟?

问题描述 投票:0回答:4

这是我的代码。

在第4行,我想在鼠标进入lastItemsLink 2秒后运行this.openList。

我怎样才能做到这一点?

lastItemsLink = $(".last-items"),
openLastItemsList = {
    init: function() {
        lastItemsLink.on("mouseenter", this.openList);
        lastItemsLink.on("mouseleave", this.closeList);
    },
    openList: function() {
        lastItemsContainer.stop(false, true).slideDown("fast");
    },
    closeList: function() {
        lastItemsContainer.stop(false, true).fadeOut("fast");
    }
};
javascript jquery mouseevent onmouseover
4个回答
2
投票

你可能需要做类似的事情

lastItemsLink = $(".last-items"),
openLastItemsList = {
    init: function () {
        lastItemsLink.on("mouseenter", this.openList);
        lastItemsLink.on("mouseleave", this.closeList);
    },
    openList: function () {
        openLastItemsList.timer = setTimeout(function () {
            lastItemsContainer.stop(false, true).slideDown("fast");
            delete openLastItemsList.timer;
        }, 2000)
    },
    closeList: function () {
        if (openLastItemsList.timer) {
            clearTimeout(openLastItemsList.timer)
        } else {
            lastItemsContainer.stop(false, true).fadeOut("fast");
        }
    }
};

演示:小提琴


1
投票

使用setTimeout

lastItemsLink.on("mouseenter", function () {
    setTimeout(this.openList, 2000)
});

1
投票

尝试 .delay() 函数 点击这里

this.delay(2000).openList

也许可以尝试一下...


0
投票

解决方案:

$('#a').mouseenter(e => {
    if (timeout != null) { clearTimeout(timeout); }
    timeout = setTimeout(function () {
        console.log('mouseenter after delay');
    }, 500);
})
.mouseleave(e => { if (timeout != null) { clearTimeout(timeout); timeout = null; } });
var timeout; 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="a">[Hover at me]</div>

© www.soinside.com 2019 - 2024. All rights reserved.