2012-08-03 133 views
0

我試圖在鼠標懸停時顯示一個div。如何在鼠標懸停上顯示/隱藏div

我正在使用jQuery 1.3。

這是我有:

$('#hoveroverthis').hover(function() {$('#showbox').show()}); 

不應該工作的呢?

編輯:固定。感謝大家!

+0

JS代碼是罰款:http://jsfiddle.net/9pNdm/所以請張貼有包含在自提琴顯示你的嘗試的例子。 – fcalderan 2012-08-03 08:13:45

+0

如果#hoveroverthis可能在另一個div類中,它會影響嗎? – Senkou 2012-08-03 08:17:11

+0

nope,它會查找帶有您提到的ID的元素,它不關心其「父」是誰。 – 2012-08-03 08:18:28

回答

0

權威的答案,這個問題是:,應該工作假設你已經輸入了正確的元素ID和元素在腳本運行時存在這些ID。

要確保文檔已準備好被JavaScript處理,請將代碼包裝到文檔「就緒」事件的句柄中。 jQuery有這個快捷方式:

$(function() { 
    // Everything in this context will be executed when the document is ready 
    $('#hoveroverthis').hover(function() {$('#showbox').show()}); 
}); 
+0

此腳本包含在標記 – Senkou 2012-08-03 08:19:57

+0

@Senkou:那就解釋一下。由於您的腳本在創建頁面中的元素之前運行,因此沒有任何反應。代之以在我的答案中使用代碼,它會起作用。 – Hubro 2012-08-03 08:20:56

1

可以在$.document.ready()功能編寫代碼,並檢查它

+0

這是做什麼的? – Senkou 2012-08-03 08:19:25

+0

將在DOM加載後將事件綁定到元素 – bugwheels94 2012-08-03 08:20:40

+0

@Senkou檢查它http://docs.jquery.com/Tutorials:Introducing_$(document).ready() – Hkachhia 2012-08-03 08:23:35

0

您可以使用此:

$(document).ready(function(){//when document is ready (loaded) these functions will initialise 
    $('#hoveroverthis').hover(function() { 
    $('#showbox').show() 
    },function() {//mouseleave event 
    $('#showbox').hide() 
    }); 
}); 
相關問題