【问题标题】:Insert text before and after the selected text in javascript在javascript中的选定文本之前和之后插入文本
【发布时间】:2013-04-24 01:30:09
【问题描述】:

我想在 HTML 文档中的任何选定文本之前和之后放置一些指定的文本(如果可能/任何可编辑字段)。 document.getSelection()document.selection.createRange().text 只返回文本本身而不是位置。 反正有没有替换选定的文本?无论如何要在文档中任何位置的选定文本之前和之后插入特定文本?

【问题讨论】:

  • 你能不能得到字符串,在开头和结尾添加你想要的,然后重新插入到原来的位置?
  • 如何“重新插入”到“原始位置”

标签: javascript


【解决方案1】:

这里有一个跨浏览器功能可以做到这一点,它适用于所有主流浏览器,并且与其他浏览器相比,它迎合了 IE 实现这一点的截然不同的方式。

现场示例:http://jsfiddle.net/timdown/UWExN/64/

function insertHtmlAtSelectionEnd(html, isBefore) {
    var sel, range, node;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = window.getSelection().getRangeAt(0);
            range.collapse(isBefore);

            // Range.createContextualFragment() would be useful here but was
            // until recently non-standard and not supported in all browsers
            // (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.collapse(isBefore);
        range.pasteHTML(html);
    }
}

【讨论】:

  • 对不起,我的参数错误
  • @LifeH2O:有什么问题?
  • 在 Internet Explorer 8 中,我在“range.pasteHTML(html);”处收到未指定的错误其中 isAfter 为真,而 html 是“文本”
  • 看到这个jsfiddle.net/srGqE 当我点击按钮上方的空白区域然后点击它时,在文本区域之前添加了“文本”
  • @LifeH2O:我确实把isAfter 参数弄错了,而是改为isBefore
【解决方案2】:

试试这个:

var r = document.selection.createRange();

r.text = "before" + r.text;
r.text += "after";

【讨论】:

  • @Tim:对于其他人来说是 window.getSelection ().getRangeAt ( 0 ).insert/appendNode ( document.createTextNode ( "before/after" ) );
  • 这也将从当前选择中删除任何 HTML 并仅将其替换为文本。
最近更新 更多