在内容可编辑div中的光标处插入文本 [英] Insert text at cursor in a content editable div

查看:128
本文介绍了在内容可编辑div中的光标处插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个contenteditable div,我需要在插入位置插入文本,

I have a contenteditable div where I need to insert text at the caret position,

这可以通过文件在IE中轻松完成。 selection.createRange()。text =banana

在Firefox / Chrome中有类似的方法吗?

Is there a similar way of implementing this in Firefox/Chrome?

(我知道存在一个解决方案这里,但它不能在contenteditable div中使用,看起来很笨拙)

(I know a solution exists here , but it can't be used in contenteditable div, and looks clumsy)

谢谢你好!

推荐答案

以下函数将在插入符号位置插入文本并删除现有选择。它适用于所有主流桌面浏览器:

The following function will insert text at the caret position and delete the existing selection. It works in all the mainstream desktop browsers:

function insertTextAtCursor(text) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode( document.createTextNode(text) );
        }
    } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().text = text;
    }
}

更新

根据评论,这里有一些用于保存和恢复选择的代码。在显示上下文菜单之前,您应该将 saveSelection 的返回值存储在变量中,然后将该变量传递到 restoreSelection 隐藏上下文菜单之后和插入文本之前恢复选择。

Based on comment, here's some code for saving and restoring the selection. Before displaying your context menu, you should store the return value of saveSelection in a variable and then pass that variable into restoreSelection to restore the selection after hiding the context menu and before inserting text.

function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function restoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}

这篇关于在内容可编辑div中的光标处插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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