javascript替换选择所有浏览器

标签 javascript selection

是否有一个简单的 js 函数可以用来用我的一些 html 替换当前文档的选择?

例如,文档包含 <p>AHAHAHA</p>在某处,用户选择第一个“ha”文本 block 。

现在我想用类似的东西替换它:<span><font color="red">hoho</font></span>

当我在谷歌上搜索 *javascript replace selection * 时,我无法得到简单直接的答案!

最佳答案

是的。以下将在所有主流浏览器中执行此操作,之后可以根据评论中的要求选择插入的内容(尽管这部分未针对 IE <= 8 实现):

现场演示:http://jsfiddle.net/bXsWQ/147/

代码:

function replaceSelection(html, selectInserted) {
    var sel, range, fragment;

    if (typeof window.getSelection != "undefined") {
        // IE 9 and other non-IE browsers
        sel = window.getSelection();

        // Test that the Selection object contains at least one Range
        if (sel.getRangeAt && sel.rangeCount) {
            // Get the first Range (only Firefox supports more than one)
            range = window.getSelection().getRangeAt(0);
            range.deleteContents();

            // Create a DocumentFragment to insert and populate it with HTML
            // Need to test for the existence of range.createContextualFragment
            // because it's non-standard and IE 9 does not support it
            if (range.createContextualFragment) {
                fragment = range.createContextualFragment(html);
            } else {
                // In IE 9 we need to use innerHTML of a temporary element
                var div = document.createElement("div"), child;
                div.innerHTML = html;
                fragment = document.createDocumentFragment();
                while ( (child = div.firstChild) ) {
                    fragment.appendChild(child);
                }
            }
            var firstInsertedNode = fragment.firstChild;
            var lastInsertedNode = fragment.lastChild;
            range.insertNode(fragment);
            if (selectInserted) {
                if (firstInsertedNode) {
                    range.setStartBefore(firstInsertedNode);
                    range.setEndAfter(lastInsertedNode);
                }
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE 8 and below
        range = document.selection.createRange();
        range.pasteHTML(html);
    }
}

例子:

replaceSelection('<span><font color="red">hoho</font></span>', true);

关于javascript替换选择所有浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5393922/

相关文章:

keyboard-shortcuts - Sublime Text、Atom 中是否有选择光标下单词的快捷方式

expression - Sublime Text 2 : Select lines that match search terms

javascript - 识别网页中选中的文本是否为粗体

javascript - 在 Telerik RadGrid 中单击复选框打开对话框窗口

javascript - 单击按钮永久删除计时器

javascript - 使用 html5 和 jQuery 绘制按钮图

javascript - 最小的 JavaScript 所见即所得 - 如果已存在,则从所选文本中删除标签

macos - 如何在 IntelliJ macOS 中禁用 block 选择

javascript - Strongloop 中的基本身份验证

javascript - 如何发出get请求来检索elasticsearch集群中某个索引的最新文档?