在textarea中启动输入暂停时,我用它来触发一个函数:
var keyTimer;
$("#TEXTAREA").on('keyup mouseup', function(){
if (keyTimer) {
clearTimeout(keyTimer);
}
keyTimer = setTimeout(function () {
doFunction(); // Not working, triggers only once (on focus).
}, 500);
});
doFunction()仅在第一次键盘暂停(焦点上)时触发。该功能必须在每次暂停时触发(500)。现在我需要模糊TEXTAREA,然后再次关注它以重新激活对我来说无用的doFunction()。非常感谢任何解决方案。
更新:
更新了代码:
var keyTimer;
$("#TEXAREA").on('keyup mouseup', function(){
if (keyTimer) {
clearTimeout(keyTimer);
}
keyTimer = setTimeout(function () {
doFunction(); // Formulates a string
$("#TEXAREA").trigger('change');
}, 500);
}).on('change', function(){
alert('test'); // This triggers at every keyup/mouseup delay (500)
// This section of code must work after delay (500), but it doesn't,
// it only works on Textarea blur, which is not what I want:
var txtarea = $(this);
var livecount = $("#myValue").val(); // Comes from doFunction()
if ( livecount.length > 2800 ) {
txtarea.css('color','#C00'); // Change text color of textarea
} else if ( livecount.length <= 2800 ) {
txtarea.css('color','#000'); // Change text color of textarea
}
});
答案 0 :(得分:0)
看起来你的代码中唯一想到的是你在doFunction中使用的选择器。您正在使用#myValue但实际上正在寻找#TEXTAREA内部的值。这是我的jsfiddle
function doFunction(){
console.log('not a test')
}
var keyTimer;
$("#TEXAREA").on('keyup mouseup', function(){
if (keyTimer) {
clearTimeout(keyTimer);
}
keyTimer = setTimeout(function () {
doFunction(); // Formulates a string
$("#TEXAREA").trigger('change');
}, 1000);
}).on('change', function(){
console.log('test'); // This triggers at every keyup/mouseup delay (500)
// This section of code must work after delay (500), but it doesn't,
// it only works on Textarea blur, which is not what I want:
var txtarea = $(this);
var livecount = $("#TEXAREA").val(); // Comes from doFunction()
if ( livecount.length > 2800 ) {
txtarea.css('color','#C00'); // Change text color of textarea
} else if ( livecount.length <= 2800 ) {
txtarea.css('color','#f00'); // Change text color of textarea
}
});
答案 1 :(得分:0)
更新 - 最终
好的,最后让它工作了:
var keyTimer;
$("#TEXTAREA").on('keyup mouseup', function(){
$(this).change(); // Need this to update keyboard character input
}).on('change', function(){
if (keyTimer) {
clearTimeout(keyTimer);
}
keyTimer = setTimeout(function () {
doFunction(); // Formulates a string
}, 200); // Delay before doFunction() so it won't slow down keyboard input
var livecount = $("#myValue"); // String value from doFunction()
if ( livecount.val().length > 2800 ) {
$(this).css('color','red'); // Change textarea text color to red for overlimit
} else if ( livecount.val().length <= 2800 ) {
$(this).css('color','black'); // Change textarea text color to black for within limit
}
});
这是漫长的一天; - )