我正在尝试向textBox中添加新行,并使用以下代码在JavaScript中使用换行符更新textBox值:
ele.value = ele.value + "\n"; ele.focus(); // To update cursor position to recently added character in textBox ele.setSelectionRange(value.length,value.length);
上面的代码更新了textBox值,但没有将光标位置更新为新行.
(虽然当我单击textBox外部并再次单击textBox内部时它会更新光标位置,但是当textBox已经被用户编辑时却没有.)
最佳答案
这应该也适用于Firefox:
HTML:
<!DOCTYPE html><html> <head><Meta charset="utf-8"><Meta name="viewport" content="width=device-width">
使用Javascript:
function updateText(e) { var ele = document.getElementById('myText'); var newVal = 'Old McDonald had a farm.\n'; ele.value = newVal; ele.focus(); // To update cursor position to recently added character in textBox ele.setSelectionRange(newVal.length,newVal.length); }
我在聚焦后选择了文字.
原文链接:https://www.f2er.com/html/426929.html