2016-04-04 29 views
1

當鼠標越過我希望它隱藏,當鼠標熄滅我希望按鈕重新出現按鈕的按鈕。但我需要使用onmouseover和onmouseout。如何在鼠標移過時使用onmouseover和onmouseout隱藏和取消隱藏按鈕?

<script> 
 
function money() 
 
{ 
 
\t document.getElementById("1").style.display = "none"; 
 
} 
 

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

+0

看看文檔,看看你如何使用這些事件:http://www.w3schools.com/jsref/event_onmouseover.asp – TheDude

+0

https://api.jquery.com/mouseover/會給你回答你需要@Mike – CAllen

+0

聽起來像是誘騙用戶的好方法嗎? – adeneo

回答

1

正如你已經知道,這可他利用CSS的:hover做...
但這裏有一個JS方式:

function money (el){ 
 
\t el.style.opacity = 0; 
 
} 
 

 
function cash (el){ 
 
\t 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"/""

+0

噢,我想切換能見度WASN不太對。這仍然會導致相同的閃爍問題(儘管至少不會迴流頁面的其餘部分)。 – AgentME

+0

@AgentME使用「不透明度」固定 –

0

這裏是純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"; 
} 
+0

至少在Chrome中有相同的fla//閃爍問題。hummmm –

1

的問題是,當光標進入按鈕,然後將鼠標懸停事件被激發,元素消失,mouseout事件觸發,因爲元素消失,因此鼠標不再存在。您需要將該按鈕放在div中,然後在該div上進行鼠標移動。

相關問題