可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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);