作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我正在尝试开发右边框/Angular 具有特定 Angular (30°) 的表格。我见过一些类似的解决方案,但它们都无法在一定程度上发挥作用。如果我想从 30° 改变到 20°,我不想花太多力气。
我是一名优秀的程序员,十分优秀!