2010-12-02 92 views
0

我必須爲單個mouseover顯示兩個圖像。所以當我mouseover圖像,首先,圖像顯示,然後延時5000,圖像需要顯示相同的懸停。現在mouseout顯示原始圖像。鼠標懸停時在兩幀之間設置時間延遲

我不太熟悉JavaScript和jQuery。
有人可以給我一些關於如何做到這一點的想法。

我做什麼,

$('.image1').mouseover(function() { 

    setInterval($(this).removeClass(.image1).addClass('image-over1'),5000); 
    $(this).removeClass(.image1).addClass('image-over2'); 

    }); 
    $('.image1').mouseout(function() { 
    $(this).removeClass('image-over1'); 
    $(this).removeClass('image-over2').addClass(item); 
    }); 


    $('.image1').click(function(){ 
    document.location='index.php?page='index.php'; 
    }) 
+0

如果你可以編輯你的問題,並確保你把4個空格在源代碼的所有位之前......這使得它更容易理解你在做什麼,因爲這會使代碼格式化程序很好地顯示給我們。或者,突出顯示代碼位並在編輯器中單擊10101圖標。謝謝! – 2010-12-02 05:57:21

回答

0

.hover()功能可以讓你在同時指定鼠標懸停/鼠標移開同時,你需要做一個功能的setInterval

$('.image1').hover(function(evt) { 

    // mouse over function. 

    // DOM Element that got the mouseover. 
    var target = evt.target; 

    if (target.timer) { 
    clearTimeout(target.timer); 
    target.timer = null; 
    } 

    target.timer = setInterval(function() { 

     // $(this) will not work here, since 'this' has changed. 
     // depending on your css you shouldn't need to remove the '.image1' 
     // class, just make sure .image-over1 and .image-over2 are 
     // stronger selectors, or occur after .image1 
     $('.image1').addClass('image-over2');  

     // at this point your element will be (just guessing <img>, could be 
     // anything really: 
     // <img class="image1 image-over1 image-over2" .../> 

     // it's absolutely fine for the image to have all those classes as 
     // long as your css is correct.  

    }, 5000); 

    $('.image1').addClass('image-over1'); 

}, function(evt) { 

    // mouse out function. 

    // DOM Element that got the mouseout. 
    var target = evt.target; 

    if (target.timer) { 
    clearTimeout(target.timer); 
    target.timer = null; 
    } 

    $('.image1').removeClass('image-over1'); 
    $('.image1').removeClass('image-over2'); 

}); 


$('.image1').click(function(){ document.location='index.php?page='index.php'; }) 
+0

謝謝你馬丁。可以看到效果,但是當鼠標移出時效果會變爲無限循環。如何停止無限循環。 Plz幫助我 – Batuli 2010-12-02 07:40:24

0

首先,我覺得有一個在你的方法有問題;如果從鼠標懸停的元素中刪除「image1」類,那麼該元素將不會與鼠標懸停的$(「。image1」)選擇器匹配。是否有理由需要刪除它?如果你這樣做(即,如果你需要禁用CSS中的類定義的東西),是否有其他一些選擇器可以匹配?

至於時間延遲,如果你使用jQuery的版本大於1.4,則可以使用.delay()函數:

$('.image1').mouseover(function() { 
$(this).addClass('image-over1').delay(5000).addClass('image-over2'); 
}); 
+0

我的jquery版本是1.3.2。我無法修改jquery,因爲它提供了其他代碼。你能以其他方式給我建議嗎?當鼠標移出時,兩幀會以相同的時間延遲迴到原始狀態,因爲我試圖給動畫效果。 – Batuli 2010-12-02 07:42:05