在事件侦听器之后更改元素

change an element back after eventlistener

我有一个元素 (const catchMe = document.getElementById("catchMe") 从鼠标“逃跑”,它通过调用一个“移动”函数 catchMe.addEventListener('mouseenter', move) 来做到这一点,该函数只是将它设置为 css style.top 等页面上的随机点('running' 也是通过 css 转换完成的)。

我想要做的是让 catchMe 元素在 mounseleave 后几秒后移回其原始位置,因此我添加了一个 eventListener catchMe.addEventListener('mouseleave',startPosition) 来重写它的原始位置 css 但里面有一个 setTimeout。 但问题是,如果我再次 mouseEnter 它不会等待几秒钟直到它调用 startPosition,因为之前的 mouseLeave 仍然处于活动状态,

所以问题是,有没有办法在新的 mouseEnter 时取消 'old' mouseLeave?还是一般情况下有更简单的方法来解决这个问题?

我使用的是简单的 javascript

const catchMe = document.getElementById('catchme');

let timeout;
catchMe.addEventListener('mouseenter', function(event){
  clearTimeout(timeout);
  this.style.backgroundColor = '#fff';
});

catchMe.addEventListener('mouseleave', function(event){
  timeout = setTimeout(() => {
    this.style.backgroundColor = '#888';
  }, 1000);
});
#catchme {
    background-color: #888;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <button id='catchme'>Catch me</button>
</body>
</html>

也许你是这个意思?我把 clearTimeout() 放在 mouseenter

我建议您的最佳选择是转播 CSS 类.

示例:

CSS

#catchMe{
position: absolute;
}

.Move{
top:20px;
}

.startPosition{
top:0px;
}

JavaScript

catchMe.addEventListener('mouseenter', () => {
catchMe.classList.add('Move');
catchMe.classList.remove('startPosition');
})

catchMe.addEventListener('mouseleave', () => {
catchMe.classList.remove('Move');
catchMe.classList.add('startPosition');
})

希望这个方法能帮到你。