Focus textarea with caret after text in Android browser

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

I am currently writing a simple webapp to view tweets in the Android browser. I am using this code to focus the caret after the current text:

var oldContent = document.tweetBox.tweet.value; document.tweetBox.tweet.value = ''; document.tweetBox.tweet.focus(); document.tweetBox.tweet.value = oldContent + to; 

This code works flawlessly in Chrome, Fluid, Opera, Firefox en Safari.
The weirdest part is that the cursor starts blinking AFTER the 'to' text if I use my hardware keyboard but the text that I enter starts where I was typing before the JS above was executed.
If I use the soft keyboard the text entering starts at the start of the textarea.

p.s The javascript is part of a suggestion for followers, so if you start typing @gn it will suggest @gnur_nl in a seperate div and when you press enter this entry is chosen.

Update: This behaviour seems to be the result of a browser bug, a bug report has been filed.

回答1:

Sounds like a browser bug. Try setting the caret position manually:

var textArea = document.tweetBox.tweet, oldContent = textArea.value; textArea.value = oldContent + to; textArea.focus(); textArea.selectionStart = textArea.selectionEnd = textArea.value.length; 


回答2:

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 ();     } }; 

and setting to the right positions

setCaret(document.getElementById("area"),document.getElementById("area").value.length); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!