如何找到一个CONTENTEDITABLE DIV光标位置? [英] How to find cursor position in a contenteditable DIV?

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

问题描述

我写一个autocompleter为内容可编辑DIV(需要渲染在文本框中输入HTML内容。所以preferred在TEXTAREA使用CONTENTEDITABLE DIV)。现在,我需要找到光标位置的时候有一个在DIV一个KEYUP /的keydown / Click事件。所以,我可以插入在该位置的HTML /文本。我无言以对我如何通过一些计算发现它还是有一个原生的浏览器功能,将帮助我找到一个contententeditable 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的意见,我建议用我自己的四肢瘦长库,它增加了一个包装器IE 的TextRange 对象,就像一个DOM范围。一个 DOM范围由开始和结束边界,每个在一个节点的条款和条件,该节点内​​的偏移pssed前$ p $,并为操作范围一堆的方法。该 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.

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

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