【发布时间】:2017-01-16 08:41:05
【问题描述】:
如何使用 javascript 在 textarea 中选择前后插入文本? 选择发生在 HTML 表单的文本区域字段中
【问题讨论】:
-
您需要广泛的浏览器支持还是现代浏览器就足够了(换句话说,至少在 9 出现之前没有 IE)?
标签: javascript
如何使用 javascript 在 textarea 中选择前后插入文本? 选择发生在 HTML 表单的文本区域字段中
【问题讨论】:
标签: javascript
在 IE、MFF 和 GC 中都可以使用的简单脚本,其中 myField 是对象引用。由通过网络找到的几个脚本组合而成。
function insertAtCursor(myField, myValueBefore, myValueAfter) {
if (document.selection) {
myField.focus();
document.selection.createRange().text = myValueBefore + document.selection.createRange().text + myValueAfter;
} else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValueBefore+ myField.value.substring(startPos, endPos)+ myValueAfter+ myField.value.substring(endPos, myField.value.length);
}
}
【讨论】:
myField.focus(); myField.selectionStart = startPos + myValueBefore.length; myField.selectionEnd = endPos + myValueBefore.length; 将此代码插入到末尾的“if else”条件中。
尝试以下方法:
var selectionText = yourTextarea.value.substr(yourTextarea.selectionStart, yourTextarea.selectionEnd);
yourTextarea.value = "Text before" + selectionText + "Text after";
如果你想搜索 + 替换,那么下面的代码就可以解决问题(在非 IE 浏览器中)
var textBeforeSelection = yourTextarea.value.substr(0, yourTextarea.selectionStart);
var textAfterSelection = yourTextarea.value.substr(yourTextarea.selectionEnd, yourTextarea.value.length);
yourTextarea.value = textBeforeSelection + " new selection text " + textAfterSelection;
【讨论】: