gpt4 book ai didi

javascript - 如何在没有 jquery 的情况下执行 hoverintent?

转载 作者:行者123 更新时间:2023-11-30 18:24:09 26 4
gpt4 key购买 nike

我不想在我的所有页面中都包含 jquery,但我在悬停某个部分时添加了一个全局“弹出”菜单,但我不希望它立即出现,因为移动鼠标时它很烦人.通常我会使用 jquery 和 hoverintent 来执行此操作,但这次不会。

我想我可以为该区域在 onmouseover 上设置超时,但不确定它是否就是这么简单(比如,当鼠标移动时它不会触发数千次吗?)

现在的代码是这样的...

<div onMouseOver="showCart();">Hover here!</div>

那么将其更改为这项工作?:

<div onMouseOver="setTimeout(showCart, 50);">Hover here!</div>

最佳答案

这是一个非常简单的 Vanilla DOM 方法。这需要一个带有 id target 的元素(对于菜单项)和一个带有 id 'dropdown' 的元素。

请注意,这使用了全局旧式“on”处理程序,这可能不是最佳实践(您应该使用 addEventListener),但是,我认为这会使代码更具可读性:)

我还设置了一个 jsFiddle here

var target = document.getElementById('target');
var dropdown = document.getElementById('dropdown');
var curEl;

document.onmousemove = function(e) {
e = e || window.event;
curEl = e.target || e.srcElement;
}

target.onmouseover = function(e) {
setTimeout(function() {
if (curEl === target || curEl === dropdown) {
dropdown.style.display = "block";
} else {
dropdown.style.display = "none";
}
}, 300);
}

target.onmouseout = dropdown.onmouseout = function() {
setTimeout(function() {
if (curEl !== target && curEl !== dropdown) {
dropdown.style.display = "none";
}
}, 300);
}

关于javascript - 如何在没有 jquery 的情况下执行 hoverintent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11348491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com