这是我的代码。
在第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");
}
};
你可能需要做类似的事情
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");
}
}
};
演示:小提琴
使用setTimeout:
lastItemsLink.on("mouseenter", function () {
setTimeout(this.openList, 2000)
});
解决方案:
$('#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>