2011-10-27 42 views
1

我對jquery瞭解不多,但我知道這是我實現這種效果的唯一方法。jquery在mouseenter div上開始倒計時,然後在「0」上顯示圖像

代碼的時刻:

JQUERY:

<script type="text/javascript"> 
    var settimmer = 0; 
    $(function(){ 
      window.setInterval(function() { 
       var timeCounter = $("b[id=show-time]").html(); 
       var updateTime = eval(timeCounter)- eval(1); 
       $("b[id=show-time]").html(updateTime); 

       if(updateTime <= 0){ 
        $("#timer").load("images/logo.png"); 
       } 
      }, 1000); 

    }); 
</script> 

HTML:

<div id="timerwrap"> <div id="my-timer"> <b id="show-time">100</b> </div> </div> 

我想知道它任何人都可以幫助它,所以當我的MouseEnter周邊div的,倒計時開始然後在定時器命中「0」時在#timerwrap中更改背景圖像?

非常感謝。

回答

0

第一個幾點。

使用身份證時,您不需要像b[id=show-time]這樣的選擇器,只需使用#show-time即可。

其次,你應該總是避免eval,加上你真正想要的是parseInt - 當然你永遠不需要評估字面數。

var updateTime = parseInt(timeCounter,10) - 1; 

現在,爲了回答你的問題,你EED執行你的函數在事件處理中的mouseover。此外,你應該只啓動定時器一次,記得當它到達0

$(function(){ 
    var timerId = 0; 
    $('#timerwrap').mouseover(function(){ 
     if(timerId == 0){ 
      timerId = window.setInterval(function() { 
       var timeCounter = $("#show-time").html(); 
       var updateTime = parseInt(timeCounter,10) - 1; 
       $("#show-time").html(updateTime); 

       if(updateTime <= 0){ 
        clearTimeout(timerId); 
        $("#timer").css({background:"url(images/logo.png)"}); 
       } 
      }, 1000); 
     } 
    }); 
}); 

阻止它活生生的例子:http://jsfiddle.net/vEsxC/

+0

這正是我一直在尋找!非常感謝你的幫助和解釋。 還有一個小問題:當我將#show-time更改爲#container4時,它不起作用。我究竟做錯了什麼? –

+0

我的意思是,如果我想通過鼠標懸停啓動計時器,而不使用定時器,再次感謝。 –

+0

不用擔心。我想到了。我覺得這樣的n00b。謝謝! –