3
因此,我正在一個文本編輯器在一個textarea我處理用戶輸入,包括標籤。每次用戶輸入內容時,我都會運行一個paginate()函數,在頁面上正確分頁文本,這個函數大約需要20毫秒。現在,因爲我不想在textarea分頁時處理第二個輸入,所以我添加了一個條件,但這樣我就失去了ctrl-V的功能。所以,按照@Gabriel Gartz的建議在這篇文章中:textarea on input issue問題textareas編輯
我通過先保存上下文和事件再次調用函數。該函數再次被調用,但粘貼仍然不會發生!
HTML:
<textarea id="taEditor"></textarea>
的javascript:
$("#taEditor").on('click keydown cut paste', processUserInput);
var IsProcessingEvent = false;
function processUserInput(e) {
if(!IsProcessingEvent) {
IsProcessingEvent = true;
//do various stuff before the textarea changes like: get value, get cursor pos etc
var taValueBefore = document.getElementById("taEditor").value;
if (e.keyCode === 9) {
e.preventDefault();
e.stopPropagation();
document.getElementById("taEditor").value += "\t";
}
getcursorpos();
//do various stuff after the textarea changes like: get value, get cursor pos etc
setTimeout(function() {
var taValueAfter = document.getElementById("taEditor").value;
getcursorpos();
if (taValueAfter !== taValueBefore) {
paginate(); //this function paginates the text in the textarea and sets the cursor
//paginate() takes about 20 milliseconds
}
if (doAgain.repeat) {
var lastEvent = doAgain;
doAgain.repeat = false;
document.getElementById("debug").innerHTML += "rerun: " + lastEvent.ctx.id + ":" + lastEvent.e.type + "<br>";
setTimeout(processUserInput.bind(lastEvent.ctx), 0, lastEvent.e);
}
document.getElementById("debug").innerHTML += e.type + "<br>";
IsProcessingEvent = false;
}, 0);
} else {
//save context and event
document.getElementById("debug").innerHTML += "isprocessing: " + e.type + "<br>";
doAgain = {
ctx: this,
e: e,
repeat: true
};
//i need to preventdefault here, because processUerInput also processes the TAB key and if i don't use preventdefault then the cursor will move focus to other elements during the pagination
e.preventDefault();
e.stopPropagation();
return false;
}
}
var doAgain = {
ctx: "",
e: "",
repeat: false
};
function getcursorpos() {
//for simplicity reasons it's empty
}
function paginate() {
var i = 0;
var k = 0;
//simulate 20-30 milliseconds of delay for pagination
for (i=0;i<100000000;i++) {
k++;
}
//for simplicity reasons it's empty
}
的jsfiddle:
來重現問題:嘗試在textarea的CTRL-V。
我不明白我做錯了什麼。在此先感謝您的幫助。
編輯
這裏是一個新的jsfiddle其中i換成了
setTimeout(processUserInput.bind(lastEvent.ctx), 0, lastEvent.e);
符合
setTimeout(function() {
processUserInput.call(lastEvent.ctx, lastEvent.e);
}, 0);
因爲.bind不跨瀏覽器,仍然不工作。
你在哪裏使用_Promises_?它在標題中,但從未提及。 – Halcyon
@FritsvanCampen更正了標題。 – MIrrorMirror
FWIW,使用'e.which',而不是'e.keyCode' – Ian