jquery 如何在on(“mouseenter”)2秒后延迟?

qyzbxkaa  于 2023-10-17  发布在  jQuery
关注(0)|答案(4)|浏览(126)

这是我的代码。
在第4行,我想在鼠标进入lastItemsLink后2秒运行这个.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");
    }
};
jjjwad0x

jjjwad0x1#

你可能需要做一些事情,

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");
        }
    }
};

演示:Fiddle

qqrboqgw

qqrboqgw2#

使用setTimeout

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

mi7gmzs63#

Try .delay()函数click here

this.delay(2000).openList

可能会起作用,给予试一试.

pkmbmrz7

pkmbmrz74#

解决方案:

$('#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>

相关问题