[英]Focus textarea with caret after text in Android browser
我目前正在編寫一個簡單的webapp來查看Android瀏覽器中的推文。 我正在使用此代碼將焦點集中在當前文本之后:
var oldContent = document.tweetBox.tweet.value;
document.tweetBox.tweet.value = '';
document.tweetBox.tweet.focus();
document.tweetBox.tweet.value = oldContent + to;
此代碼在Chrome,Fluid,Opera,Firefox和Safari中完美運行。
最奇怪的部分是,如果我使用我的硬件鍵盤,光標開始在'到'文本后開始閃爍,但我輸入的文本開始於我在執行JS之前輸入的位置。
如果我使用軟鍵盤,文本輸入將從textarea的開頭開始。
ps javascript是關注者建議的一部分,所以如果你開始輸入@gn,它會在單獨的div中建議@gnur_nl,當你按回車時,這個條目被選中。
更新:此行為似乎是瀏覽器錯誤的結果, 已提交錯誤報告 。
聽起來像瀏覽器錯誤。 嘗試手動設置插入位置:
var textArea = document.tweetBox.tweet, oldContent = textArea.value;
textArea.value = oldContent + to;
textArea.focus();
textArea.selectionStart = textArea.selectionEnd = textArea.value.length;
setCaret = function(obj,pos) {
// IE Support
if (document.selection) {
// Set focus on the element
obj.focus ();
// Create empty selection range
var oSel = document.selection.createRange ();
// Move selection start and end to 0 position
oSel.moveStart ('character', -obj.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', pos);
}
//standard browsers
else if (obj.selectionStart || obj.selectionStart == '0') {
obj.selectionStart = pos;
obj.selectionEnd = pos;
obj.focus ();
}
};
並設置到正確的位置
setCaret(document.getElementById("area"),document.getElementById("area").value.length);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.