[英]How to use onmouseover and onmouseout to hide and unhide a button when the mouse goes over it?
当鼠标移到按钮上方时,我希望它隐藏;当鼠标移到按钮上方时,我希望按钮重新出现。 但是我需要使用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('')" >
如您所知,他可以使用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)">
因此,可以,使用opacity
, mouseenter
和mouseleave
并传递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"/""
。
问题在于,当光标进入按钮时,将触发mouseover事件,该元素消失,由于该元素消失而触发mouseout事件,因此鼠标不再在其中。 您需要将按钮放在div中,然后将鼠标移出该div。
这是纯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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.