如何在函数计算的输入变化上更改文本字段?

时间:2018-01-06 15:43:01

标签: jquery function calculator timecodes

这是我的时间码计算器。当我更改输入字段值时,时间码也应该更改。



var fps = 25;
var currentFrame =  $('.timecode_input').val();
var SS = Math.floor(currentFrame / fps);
var MM = Math.floor(SS / 60);
var HH = Math.floor(MM / 60);
var FF = currentFrame - (SS * fps);

function pad(str, width, what, left) {
    str = String(str);
    what = String(what);
    var w = width - str.length;

    if (left) {
        return (new Array(w + 1)).join(what) + str;
    } else {
        return str + (new Array(w + 1)).join(what);
    }
}

var i,
    timecode = [HH, MM, SS, FF];

for (i = 0; i < timecode.length; i += 1) {
    timecode[i] = pad(timecode[i], 2, 0, true);
}

var resultString = timecode.join(':'); // HH:MM:SS:FF

var timecode_p = document.querySelector('.timecode_output'),
    input = document.querySelector('.timecode_input');

function setText(v){
    timecode_p.innerHTML = resultString;
     console.log(resultString);
}

input.addEventListener('input', function(){ 
    setText( this.value );
    console.log(this.value );
})

setText(input.value);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="timecode_input" type="text" value="25" style="width:90%"> Frames
<p class="timecode_output" style="margin-top:10px"></p>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

所有这些代码都需要在函数内部并在事件中被调用(可能不是var定义)。

这是因为事件只调用了更新innerHTML属性的setText方法。它实际上从未改变你的时间码变量。

var fps = 25;
var currentFrame =  $('.timecode_input').val();
var SS = Math.floor(currentFrame / fps);
var MM = Math.floor(SS / 60);
var HH = Math.floor(MM / 60);
var FF = currentFrame - (SS * fps);


var i,
    timecode = [HH, MM, SS, FF];

for (i = 0; i < timecode.length; i += 1) {
    timecode[i] = pad(timecode[i], 2, 0, true);
}

var resultString = timecode.join(':'); // HH:MM:SS:FF