gpt4 book ai didi

javascript - 定时鼠标悬停后激活弹出菜单,然后在鼠标移开时取消激活

转载 作者:行者123 更新时间:2023-11-30 16:39:14 25 4
gpt4 key购买 nike

我正在尝试制作一个菜单,当您将鼠标悬停在某个元素上一段时间后,该菜单就会出现。如果您将鼠标悬停在该元素上,但在设定时间之前鼠标移出,则不会出现菜单。这个想法是为了防止用户在简单地将鼠标快速移过元素时意外激活菜单。

默认情况下,菜单在我的 CSS 中设置为 display:none;。然后,当他们成功悬停足够长的时间时,我向其添加一个 .active 类以将显示设置为 block.

我的问题是,一旦鼠标在元素上停留的时间足够长(在我的测试用例中,我将其设置为 1 秒),将鼠标移到新显示的菜单上会被视为鼠标移开,我会丢失菜单。我曾假设,因为菜单是我正在收听的元素的子元素,所以它仍然算作鼠标悬停在该元素上。我想我错了!

Amazon.com's main menu是我正在努力实现的一个很好的例子。

这是我的 HTML。

<div id="drop-nav-trigger">
Menu

<div class="drop-nav">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</div>

</div>

这是我的 javascript。我混杂了一些 jQuery 用于更改我的菜单类。

var timeoutId = null;
var el = document.getElementById("drop-nav-trigger");

/* Activate menu after a delay. */
el.addEventListener('mouseover',function() {
timeoutId = window.setTimeout(function(){

$(".drop-nav").addClass("active");

}, 1000);
} );

// Cancel action if mouse moved out within 2 sec
el.addEventListener('mouseout',function() {
window.clearTimeout(timeoutId);
$(".drop-nav").removeClass("active");
});

这是一个代码笔:http://codepen.io/jimmykup/pen/EVYbWx

最佳答案

tirck 是使用 mouseleave 而不是 mouseout See Example

The mouseleave event differs from mouseout in the way it handles event bubbling. If mouseout were used in this example, then when the mouse pointer moved out of the Inner element, the handler would be triggered. This is usually undesirable behavior. The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant. So in this example, the handler is triggered when the mouse leaves the Outer element, but not the Inner element.

来源:http://api.jquery.com/mouseleave/

关于javascript - 定时鼠标悬停后激活弹出菜单,然后在鼠标移开时取消激活,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32261636/

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