【问题标题】:How to replace selected text in a textarea with Javascript?如何用Javascript替换文本区域中的选定文本?
【发布时间】:2015-06-25 23:46:43
【问题描述】:

我有一个 textarea 和一个按钮,它将以下文本添加到 textarea:

" - 列表项"

如果在 textarea 中选择了一些文本,我希望添加的文本如下所示:

" - (选定的文本)"

因此,解决此问题的方法是使用 if 函数来查看是否在 textarea 中选择了文本,如果是,则接收突出显示的文本,以便将其附加到文本中文本区域。

可以使用document.getElementById(textarea).value += string 简单地完成附加部分,但我不确定是否检查 textarea 中的某些文本是否被选中并接收它。

【问题讨论】:

    标签: javascript jquery textarea


    【解决方案1】:

    对于非 IE 浏览器,您可以使用 textarea 对象的 selectionStartSelectionEnd 属性执行以下操作:

    function createListElement() {
        if(document.activeElement === textarea) {
            if(typeof textarea.selectionStart == 'number' && typeof textarea.selectionEnd == 'number') {
                // All browsers except IE
                var start = textarea.selectionStart;
                var end = textarea.selectionEnd;
    
                var selectedText = textarea.value.slice(start, end);
                var before = textarea.value.slice(0, start);
                var after = textarea.value.slice(end);
    
                var text = before + '- ' + selectedText + after;
                textarea.value = text;
           }
       }
    }
    

    但是这种微不足道的操作对于 IE 来说越来越难了,你可以找到更多here

    希望对你有帮助:)

    【讨论】:

    • 短版:var t=textarea, s=t.selectionStart, e=t.selectionEnd, v=t.value; if(typeof s=='number' && typeof e=='number') t.value=v.slice(0, s)+'- '+v.slice(s, e)+v.slice(e);
    猜你喜欢
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多