gpt4 book ai didi

javascript - 鼠标在 div 上停留一定时间后如何调用函数?

转载 作者:行者123 更新时间:2023-12-01 01:09:47 25 4
gpt4 key购买 nike

Onmouseover 似乎会立即调用它,但我想让它在鼠标位于 div 上(例如 2 秒)后调用一个函数。

你是怎么做到的?

最佳答案

当鼠标悬停在元素顶部时,使用 setTimeout 触发该函数。如果他们在执行之前离开,则将其删除。

function hoverChange(elem, ms, action) {
// holds the interval so we know what to remove
var timer
// listen for when mouse enters and add a timer
elem.addEventListener('mouseenter', function () {
timer = window.setTimeout(action, ms)
})
// listen for when the mouse exits and remove it
elem.addEventListener('mouseleave', function () {
if(timer) window.clearTimeout(timer)
})
}

var spanElem = document.querySelector('span')
hoverChange(spanElem, 2000, function() {
spanElem.classList.toggle('yellow')
})
.yellow { background-color: yellow; }
<span>Hello World</span>

关于javascript - 鼠标在 div 上停留一定时间后如何调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55270853/

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