jQuery为文本字段的输入值设置动画

时间:2013-03-06 13:46:41

标签: jquery

我已经浏览了几个小时但仍然找不到值得的东西。

我想将文本字段的值设置为0到它的值。例如,我有一个textinput值为“100”,并且在任何事件或页面加载之后我希望这个值从0到100(输入的起始值)设置动画

我怎么能这样做?非常感谢提前!

2 个答案:

答案 0 :(得分:3)

您可以使用jQuery的“animate”功能的“step”选项对动画的每个“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?

答案 1 :(得分: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 );
}

这是fiddle example

相关问题