2010-08-05 64 views
2

我希望當鼠標懸停在圖像上時,一個事件應該被觸發一次,並且只有在鼠標不在該圖像中並且再次返回時纔會觸發事件,並且至少還要經過2秒鐘。 我現在的功能不斷(refreshcash)呼籲,如果我離開鼠標滑過我的形象JavaScript/jQuery onmouseover問題

<img src="images/reficon.png" onmouseover="refreshcash()" onmouseout="normalimg()" id="cashrefresh"/> 

function refreshcash() { 
$("#showname").load('./includes/do_name.inc.php'); 
$("#cashrefresh").attr("src","images/reficonani.gif"); 
} 

function normalimg() { 
$("#cashrefresh").attr("src","images/reficon.png"); 
} 

代碼更新 此代碼似乎有一個bug,但是算法是有點邏輯

<script type="text/javascript"> 
var canhover = 1; 
var timeok = 1; 
function redotimeok() { 
    timeok = 1; 
} 
// 
function onmenter() 
{ 
if (canhover == 1 && timeok == 1) 
    { 
    enter(); 
    canhover = 0; 
    } 
} 
// 
function onmleave() 
{ 
    leave(); 
    canhover = 1; 
    setTimeout(redotimeok(), 2000); 
    leave(); 
} 
// 
$('#cashrefresh').hover(onmenter(),onmleave()); 

function enter(){ 
    $("#showname").load('./includes/do_name.inc.php'); 
    $("#cashrefresh").attr("src","images/reficonani.gif"); 
} 

function leave(){ 
    $("#cashrefresh").attr("src","images/reficon.png"); 
} 
</script> 
+0

@Sarfraz:只是好奇:你爲什麼改變5秒鐘2秒? – 2010-08-05 19:38:17

+0

@Marcel Korpel:我沒有,只是用Cntr + K格式化了代碼,我不認爲這應該代替任何字符:) – Sarfraz 2010-08-05 19:40:08

+0

@Sarfraz:Then [that](http://stackoverflow.com/posts/ 3418472/revisions#revee94a44e-d271-4f3d-a6ab-4702bc7db9b0)*非常*很奇怪......;) – 2010-08-05 19:55:31

回答

1

你已經以某種方式緩存的圖片?如果您將它們替換爲它們的src屬性,而沒有在其他地方指定width/height(最好是CSS)或讓它們隨時可用,則懸停的框(img元素)將摺疊到較小(或不包含)框中,直到圖像加載到遠處足以讓瀏覽器知道圖像的正確尺寸以調整框的大小(這可能會影響調整爲圖像的其他元素)。確切的效果取決於瀏覽器,但您可能會失去懸停狀態,導致您的鼠標移出功能的調用。

我假設兩幅圖像的大小相同,所以如果您還沒有,可以嘗試將尺寸添加到您的CSS的#cashrefresh並查看是否解決了問題。

對於延遲,我建議使用jQuery timers plugin(或類似的),這樣可以簡化定時器的處理過程,而不是單獨進行定時器處理。在添加下一個名稱之前,您可能想要給定時器名稱並嘗試停止舊的名稱。

2

嘗試在hover

$('#cashrefresh').hover(function(){ 
    $("#showname").load('./includes/do_name.inc.php'); 
    $("#cashrefresh").attr("src","images/reficonani.gif"); 
}, function(){ 
    $("#cashrefresh").attr("src","images/reficon.png"); 
}); 

而且你的形象應該是這樣的:

<img src="images/reficon.png" id="cashrefresh"/> 

更新:

修改你的代碼是這樣的:

var e = null; 
var l = null; 

$('#cashrefresh').hover(function(){ 
    e = setTimeout(enter, 2000) 
}, function(){ 
    l = setTimeout(leave, 2000) 
}); 

function enter(){ 
    $("#showname").load('./includes/do_name.inc.php'); 
    $("#cashrefresh").attr("src","images/reficonani.gif"); 
    clearTimeout(e); 
} 

function leave(){ 
    $("#cashrefresh").attr("src","images/reficon.png"); 
    clearTimeout(l); 
} 
+0

如果我添加了這個函數,我的鼠標每秒鐘都會調用該函數,並將它放在圖像上#cashrefresh – NVG 2010-08-05 20:54:47

+0

如果我將鼠標放在圖像上,則每2秒調用一次do_name.inc.php文件。 我希望當您將鼠標懸停在圖像上並且圖像應該改變時,代碼纔會被調用一次,並且爲了防止快速鼠標懸停濫用,應該每2秒只能使用一次。 – NVG 2010-08-05 21:28:50

+0

重新檢查我的問題,也許你可以幫我:) – NVG 2010-08-05 21:29:19