2012-01-23 99 views
0

如何在特定時間間隔突出顯示div中的文本。時間間隔已經在每個div的「間隔」屬性中提及。是否有可能在setInterval或setTimeout函數中動態更改時間間隔。我已經編寫了我正在使用的HTML和jQuery代碼的結構。使用jquery突出顯示單詞

<html> 
<head> 
<style> 
    .green_class{ 
    background-color:green; 
    } 
</style> 

<script type="text/javascript"> 
    $(document).ready(function(){ 
    $("#btnclick").click(function(){ 
     var childs=$("#test").children(); 
     $(childs).each(function(){ 
     var time_interval=$(this).attr("intervals"); 
     setTimeout(function(){$(this).addClass("green_class");},parseInt(time_interval)); 
     }); 
    }); 
    }); 
</script> 
</head> 
<body> 
    <div id="test" style="float:left"> 
     <div intervals="0">Lorem&nbsp;</div> 
     <div intervals="500">Ipsum&nbsp;</div> 
     <div intervals="800">is&nbsp;</div> 
     <div intervals="1000">simply&nbsp;</div> 
     <div intervals="1200">dummy&nbsp;</div> 
     <div intervals="1400">text&nbsp;</div> 
     <div intervals="1600">of&nbsp;</div> 
     <div intervals="1800">the&nbsp;</div> 
     <div intervals="2000">printing&nbsp;</div> 
     <div intervals="2200">and&nbsp;</div> 
     <div intervals="2400">typesetting&nbsp;</div> 
     <div intervals="2600">industry</div> 
    </div> 
<input type="button" value="Highlight" id="btnclick"/> 
</body> 
</html> 

上述腳本無法正常工作。是否可以動態更改setTimeout函數的持續時間。請給出您寶貴的建議/解決方案。

回答

1

你expando屬性「間隔」應該attr("intervals")引用,不attr(intervals)

此外,我認爲你可以做childs.each,而不是$(childs).each,如childs已經是jQueryified對象。

1

傳送代碼http://jsfiddle.net/NyuWb/
您還在錯誤的上下文中調用$(this).addClass("green_class");。 所以我的版本:

$("#btnclick").click(function() { 
    $("#test").children().each(function() { 
     var time_interval = $(this).attr('intervals'), 
      _this = $(this); 

     setTimeout(function() { 
      _this.addClass("green_class"); 
     }, parseInt(time_interval)); 
    }); 
}); 
+0

它只需要一次的時間間隔。請檢查...持續時間是均勻分佈的。沒有改變。簡單地說,我的意思是時間間隔不會動態變化。舉一個例子,我已經延長到2600毫秒。但是您可以確定突出顯示的速度是一致的。請與... – Madhan

+0

您指定間隔爲800,1000,1200等與200ms增量。所以確保突出顯示是一致的速度。 – dfsq

+0

嗨,其實文本應該突出顯示其確切的時間間隔,這是在「間隔」屬性。不是兩個區間的差異。我的意思是如果間隔是800,它應該在800毫秒後突出顯示。如果間隔爲1500毫秒,則應在1500毫秒後突出顯示。可能嗎...? – Madhan