为什么这些设置事件导致鼠标悬停时闪烁?
我尝试过以下代码
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/