簡體   English   中英

當鼠標移過按鈕時,如何使用onmouseover和onmouseout來隱藏和取消隱藏按鈕?

[英]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)"> 

因此,可以,使用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"/""

問題在於,當光標進入按鈕時,將觸發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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM