如何在可编辑的 DIV 中找到光标位置? [英] How to find cursor position in a contenteditable DIV?

查看:75
本文介绍了如何在可编辑的 DIV 中找到光标位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为内容可编辑的 DIV 编写自动完成程序(需要在文本框中呈现 html 内容.因此,我更喜欢使用 contenteditable DIV 而不是 TEXTAREA).现在我需要在 DIV 中有 keyup/keydown/click 事件时找到光标位置.这样我就可以在那个位置插入 html/text.我不知道如何通过一些计算找到它,或者是否有本机浏览器功能可以帮助我在可编辑的 DIV 中找到光标位置.

I am writing a autocompleter for a content editable DIV (need to render html content in the text box. So preferred to use contenteditable DIV over TEXTAREA). Now I need to find the cursor position when there is a keyup/keydown/click event in the DIV. So that I can insert the html/text at that position. I am clueless how I can find it by some computation or is there a native browser functionality that would help me find the cursor position in a contententeditable DIV.

推荐答案

如果您只想在光标处插入一些内容,则无需明确查找其位置.以下函数会在所有主流桌面浏览器的光标位置插入一个DOM节点(元素或文本节点):

If all you want to do is insert some content at the cursor, there's no need to find its position explicitly. The following function will insert a DOM node (element or text node) at the cursor position in all the mainstream desktop browsers:

function insertNodeAtCursor(node) {
    var range, html;
    if (window.getSelection && window.getSelection().getRangeAt) {
        range = window.getSelection().getRangeAt(0);
        range.insertNode(node);
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        html = (node.nodeType == 3) ? node.data : node.outerHTML;
        range.pasteHTML(html);
    }
}

如果您更愿意插入 HTML 字符串:

If you would rather insert an HTML string:

function insertHtmlAtCursor(html) {
    var range, node;
    if (window.getSelection && window.getSelection().getRangeAt) {
        range = window.getSelection().getRangeAt(0);
        node = range.createContextualFragment(html);
        range.insertNode(node);
    } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().pasteHTML(html);
    }
}

更新

根据 OP 的评论,我建议使用我自己的 Rangy 库,它添加了一个包装器到行为类似于 DOM 范围的 IE TextRange 对象.DOM Range 由开始和结束组成边界,每个边界都用一个节点和该节点内的偏移量表示,以及一系列操作范围的方法.MDC 文章应该提供一些介绍.

Following the OP's comments, I suggest using my own Rangy library, which adds a wrapper to IE TextRange object that behaves like a DOM Range. A DOM Range consists of a start and end boundary, each of which is expressed in terms of a node and an offset within that node, and a bunch of methods for manipulating the Range. The MDC article should provide some introduction.

这篇关于如何在可编辑的 DIV 中找到光标位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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