简体   繁体   中英

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.

 <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 ...
but here's a JS way:

 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.

To recap, opacity will visually "hide" the element but keep it in place, not triggering a mouseleave due to element disappearance.


I'd also highly discourage you from using inline JS ,
keep all your logic where's it's meant to be: inside your 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.

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. You need to put the button in a div and do the mouse out on that div.

here is the pure JS way: Note that the button like the other answer will flutter: 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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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