javascript - 鼠标悬停轻拂

标签 javascript dom-events

为什么这些设置事件导致鼠标悬停时闪烁?

我尝试过以下代码

const headerTags1 = document.querySelector('h1');
headerTags1.addEventListener('mouseenter', function(event){
event.target.style.display = "none";
})
console.log(headerTags1)

const headerTags2 = document.querySelector('h1');
headerTags2.addEventListener('mouseleave', function(event){
event.target.style.display = "initial";
})
console.log(headerTags2)

最佳答案

发生这种情况是因为只要您将鼠标悬停在 h1 上,它就会隐藏,并且由于它现在已隐藏,您不再将鼠标悬停在它上面并且 mouseleave 会触发,因此然后它就会显示出来,但是当您将鼠标悬停在它上面时,它就会隐藏起来,等等。

const headerTags1 = document.querySelector('h1');
headerTags1.addEventListener('mouseenter', function(event){
event.target.style.display = "none";
})
console.log(headerTags1)

const headerTags2 = document.querySelector('h1');
headerTags2.addEventListener('mouseleave', function(event){
event.target.style.display = "initial";
})
console.log(headerTags2)
<h1>Now you see me...</h1>

当然,这从一开始就不是一个好的设计决策。你真正想实现什么目标?

编辑:

Just want to have the button disappear and reappear when it's hovered over or better yet just change colors when it's hovered over...

那么更好的方法是使用 CSS :hover pseudo-class仅在悬停时修改元素的样式。

<!doctype html>
<html>
<head>
  <title>Page Title Here</title>
  <style>
    h1:hover { opacity:0; }
    button:hover { color:red; background-color:#ff0; }  
  </style>
</head>
<body>

  <h1>Now you see me...</h1>
  <button>Hover Over Me</button>
  
</body>
</html>

关于javascript - 鼠标悬停轻拂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56368308/

相关文章:

javascript - Jquery Resizable 将 DIV 高度降低到小于默认值(即将 minHeight 降低到大约 1px)

javascript - 在 addEventListener 中调用函数而不显式传递事件对象

javascript - 有没有办法在 TypeScript 中组合类混合?

javascript - jsp在两个页面之间传递变量

javascript - Chrome 消息传递,我做错了什么?

javascript - 当我尝试格式化日期时 Chart.js 没有显示

javascript - event.pageX 在 Firefox 中不起作用,但在 Chrome 中起作用

javascript - iframe 中的元素如何捕获关键事件?

javascript - 关闭父选项卡时关闭所有子选项卡

javascript - 如何检查是否按下了某个键?