如何使用onmouseover和onmouseout在鼠标经过按钮时隐藏和取消隐藏按钮

How to use onmouseover and onmouseout to hide and unhide a button when the mouse goes over it?

本文关键字:按钮 隐藏 取消 经过 何使用 onmouseover onmouseout 鼠标      更新时间:2023-12-16

当鼠标移到按钮上时,我希望它隐藏起来,当鼠标离开按钮时,我想要按钮重新出现。但是我需要使用onmouseover和onmouseout。

<script>
function money ()
{
	document.getElementById("1").style.display = "none";
}
function cash ()
{
	document.getElementById("1").style.display = "block";
}
</script>
<input type="button" value="Hi" id="1" onmouseover="money('')" onmouseout="cash('')" >

这里是纯JS方式:注意按钮和其他答案一样会颤动:https://jsfiddle.net/omarjmh/6o2nc754/1/

var x = document.getElementById("myBtn");
x.addEventListener("mouseenter", myFunction);
x.addEventListener("mouseout", mySecondFunction);
function myFunction() {
    document.getElementById("myBtn").style.display = "none";
}
function mySecondFunction() {
    document.getElementById("myBtn").style.display = "block";
}

问题是,当光标进入按钮时,mouseover事件被触发,元素消失,mouseout事件被触发是因为元素不见了,因此鼠标不再在其中。您需要将按钮放在一个div中,然后将鼠标移到该div上。

如您所知,这可以使用CSS的:hover
但这里有一种JS方式:

function money (el){
	el.style.opacity = 0;
}
function cash (el){
	el.style.opacity = 1;
}
<input type="button" value="Hi" onmouseenter="money(this)" onmouseleave="cash(this)">

因此,是的,使用opacitymouseentermouseleave并传递this(HTMLElement)引用。

概括一下,不透明性将在视觉上"隐藏"元素,但将其保持在适当位置,不会因元素消失而触发mouseleave


我还强烈反对您使用内联JS
把你所有的逻辑都放在它应该在的地方:在你的script中:

function tog(event) {
  this.style.opacity = event.type==="mouseenter" ? 0 : 1;
}
var btn1 = document.getElementById("1");
btn1.addEventListener("mouseenter", tog);
btn1.addEventListener("mouseleave", tog);
<input id="1" type="button" value="Hi">

请注意您的按钮仍然可以点击:)
如果您不希望它是可点击的,则以父元素为目标,而不是在按钮子元素上使用display: "none"/""