在javascript中在所选文本之前和之后插入文本 [英] Insert text before and after the selected text in javascript

查看:136
本文介绍了在javascript中在所选文本之前和之后插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to put some specified text (where possible/any editable field) before and after any selected text in an HTML document. document.getSelection() or document.selection.createRange().text returns only the text itself not the position. Is there anyway to replace the selected text? Anyway to insert specific text before and after selcted text anywhere in the document?

推荐答案

这是一个跨浏览器的功能,它可以在所有主流浏览器中使用,并且与其他浏览器相比,IE可以完全不同的方式。

Here's a cross-browser function to do this, which works in all major browsers and caters for the vastly different way IE does this compared to other browsers.

实例: 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);
    }
}

这篇关于在javascript中在所选文本之前和之后插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆