2013-03-06 111 views
0

我瀏覽了好幾個小時,仍然找不到值得的東西。jQuery爲文本字段的輸入值設置動畫效果

我想將文本字段的值從0移動到它的值。例如,我有一個textinput值=「100」,在任何事件或頁面加載後,我希望此值從0到100(輸入的起始值)動畫

我怎麼能做到這一點?提前感謝!

回答

0

嘗試

$(document).ready(function(){ 
    increase($('#i')); 
}); 

function increase(i , v){ 
    // let's store the initial/original input's value 
    if(!i.data.originalValue) i.data.originalValue = i.val(); 
    var currentVal = v || 0; 
    i.val(currentVal); 
    // if current value == initial/original value, then break the script 
    if(i.val() == i.data.originalValue) { 
     alert('Complete!'); // <-- callback here 
     return; 
    } 
    currentVal++; 
    // call this function again after 30ms 
    setTimeout(increase , 30 , i , currentVal); 
} 

這裏a fiddle example

3

您可以對jQuery的'animate'函數使用'step'選項來對動畫的每個「步驟」執行操作。

//When the document is ready.. 
jQuery(document).ready(function() { 
    //..loop over all of the INPUT elements that have a non-blank data-value field.. 
    jQuery("input[data-value!='']").each(function (inputKey, inputItem) { 
     //..animate between the current value of the input (i.e. 0) and the desired 
     // value specified in the data-value field, setting to the full value upon 
     // completion of the animation 
     jQuery({ 
      value: jQuery(inputItem).val() 
     }).animate({ 
      value: jQuery(inputItem).data("value") 
     }, { 
      step: function() { 
       jQuery(inputItem).val(Math.round(this.value)); 
      }, 
      complete: function() { 
       jQuery(inputItem).val(jQuery(inputItem).data("value")); 
      } 
     }); 
    }); 
}); 

看看這個的jsfiddle例如:http://jsfiddle.net/yE86J/9/1

我推薦使用四捨五入,以確保你最終 參考文獻:http://www.josscrowcroft.com/2011/code/jquery-animate-increment-decrement-numeric-text-elements-value/jQuery how to find an element based on a data-attribute value?

+0

對不起 - 在那裏錯過了幾個大括號。 – Seidr 2013-03-06 13:52:52

+0

它不壞,謝謝 - 但我想動畫已經有它的輸入的具體價值。 – 2013-03-06 13:55:00

+1

然後,您可以更改step函數中的調用,即jQuery(「#targetInput」)。val(this.value);如果您的意思是從0到100的動畫(100位在值字段中),那麼您可以使用數據字段來存儲所需的值。加載頁面時,可以檢查頁面上的所有輸入以查看它們是否具有所需值的數據值,然後調用上述的動畫函數。我會給你發一個jsFiddle的例子。 – Seidr 2013-03-06 13:56:57

相關問題