简体   繁体   English

当鼠标移过按钮时,如何使用onmouseover和onmouseout来隐藏和取消隐藏按钮?

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

When the mouse goes over the button i want it to hide and when the mouse goes off the button i want the button to reappear. 当鼠标移到按钮上方时,我希望它隐藏;当鼠标移到按钮上方时,我希望按钮重新出现。 But i need to use onmouseover and onmouseout. 但是我需要使用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('')" > 

As you already know, this can he done using CSS's :hover ... 如您所知,他可以使用CSS的:hover ...
but here's a JS way: 但是这是一种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)"> 

So yes, use opacity , mouseenter and mouseleave and pass the this (HTMLElement) reference. 因此,可以,使用opacitymouseentermouseleave并传递this (HTMLElement)参考。

To recap, opacity will visually "hide" the element but keep it in place, not triggering a mouseleave due to element disappearance. 概括地说,不透明度将在视觉上“隐藏”元素,但将其保留在适当的位置,不会因元素消失而触发mouseleave


I'd also highly discourage you from using inline JS , 我也强烈建议您不要使用内联JS
keep all your logic where's it's meant to be: inside your script : 将所有逻辑保持在原本的位置: 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"> 

Note that you button will still be clickable :) 请注意,您的按钮仍然可以点击:)
If you don't want it to be clickable, target a parent element instead , than you can use display: "none"/"" on your button children. 如果您不希望它可单击,请改为定位父元素 ,然后在子按钮上使用display: "none"/""

The problem is that when the cursor enters the button then the mouseover event is fired, the element disappears, the mouseout event fires because the element is gone and thus the mouse isn't in it any more. 问题在于,当光标进入按钮时,将触发mouseover事件,该元素消失,由于该元素消失而触发mouseout事件,因此鼠标不再在其中。 You need to put the button in a div and do the mouse out on that div. 您需要将按钮放在div中,然后将鼠标移出该div。

here is the pure JS way: Note that the button like the other answer will flutter: https://jsfiddle.net/omarjmh/6o2nc754/1/ 这是纯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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM