我有以下JavaScript用于动态插入unicode字符(由txtToIns变量表示)到文本正文中
elmt.value = elmt.value.substring(0, elmt.selectionStart) + txtToIns + " " + elmt.value.substring(elmt.selectionStart, elmt.selectionEnd) + elmt.value.substring(elmt.selectionEnd, elmt.value.length) + " ";
elmt.focus();
elmt.value = elmt.value.trim();
Run Code Online (Sandbox Code Playgroud)
使用上面的方法,光标始终位于文本的末尾.有什么办法可以在txtToIns后直接放置它吗?不,txtToIns.focus()不起作用
我不确定你要用textarea值中的空格字符做什么,特别是最后一个将在两行之后再次修剪掉的空格,所以我忽略了下面代码中的空格.我也不确定你要对之前选择的文本(如果有的话)做什么,所以我假设你想用新文本覆盖它.
请记住,这不适用于IE <9,它不支持selectionStart,selectionStart或setSelectionRange().
演示:http://jsfiddle.net/timdown/wPfVn/
码:
var val = elmt.value;
var start = elmt.selectionStart, end = elmt.selectionEnd;
elmt.value = val.slice(0, start) + txtToIns + val.slice(end);
elmt.focus();
var caretPos = start + txtToIns.length;
elmt.setSelectionRange(caretPos, caretPos);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23163 次 |
| 最近记录: |