【问题标题】:Insert text before and after selection in textarea with javascript使用javascript在textarea中选择前后插入文本
【发布时间】:2017-01-16 08:41:05
【问题描述】:

如何使用 javascript 在 textarea 中选择前后插入文本? 选择发生在 HTML 表单的文本区域字段中

【问题讨论】:

  • 您需要广泛的浏览器支持还是现代浏览器就足够了(换句话说,至少在 9 出现之前没有 IE)?

标签: javascript


【解决方案1】:

在 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”条件中。
【解决方案2】:

尝试以下方法:

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;

【讨论】:

  • 如果你想支持它,你需要为 IE 做点别的。
  • 我认为上面的示例将替换整个 textarea 内容...也许有办法搜索和替换?
  • 如果您想搜索 + 替换,那么您可以只阅读文本直到选择,然后阅读直到结束。我将编辑上面的答案,以向您展示我的意思。
  • @Riccardo:不,jQuery 不处理这个问题,尽管有 jQuery 插件可以处理。
猜你喜欢
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多