如何得到插入符合html子元素的contenteditable div中的位置? [英] How to get caret position within contenteditable div with html child elements?

查看:469
本文介绍了如何得到插入符合html子元素的contenteditable div中的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个contenteditable div,可以选择在文本流中包含标签等内联html元素。

I am working with a contenteditable div that will have the option to have inline html elements such as tags in the text flow.

在某些点,我需要抓取但是发现如果插入符号位于html子元素之后,则返回的示例代码的位置不正确。

At certain points I need to grab the caret position but have found that with the example code the position returned is incorrect if the caret is after an html child element.

我需要一个跨浏览器解决方案这将允许我存储插入符的位置,以便即使在文本流中存在html元素,也可以稍后再恢复。

示例: http://jsfiddle.net/wPYMR/2/

推荐答案

我在这里回答了一个非常类似的问题:在IE中编辑Iframe内容 - 维护文字选择问题

I've answered a very similar question here: Editing Iframe Content in IE - problem in maintaining text selection

版本的答案:

如果你不改变contenteditable元素的内容,下面的函数将做。在做任何你需要做的事情之前调用 saveSelection(),然后 restoreSelection()如果您要更改内容,建议使用我的 Rangy 图库的保存/恢复选择模块

If you're not changing the contents of the contenteditable element then the following functions will do. Call saveSelection() before doing whatever you need to do and restoreSelection() afterwards. If you are changing the content, I'd suggest using my Rangy library's save/restore selection module.

var saveSelection, restoreSelection;
if (window.getSelection) {
    // IE 9 and non-IE
    saveSelection = function() {
        var sel = window.getSelection(), ranges = [];
        if (sel.rangeCount) {
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                ranges.push(sel.getRangeAt(i));
            }
        }
        return ranges;
    };

    restoreSelection = function(savedSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
        for (var i = 0, len = savedSelection.length; i < len; ++i) {
            sel.addRange(savedSelection[i]);
        }
    };
} else if (document.selection && document.selection.createRange) {
    // IE <= 8
    saveSelection = function() {
        var sel = document.selection;
        return (sel.type != "None") ? sel.createRange() : null;
    };

    restoreSelection = function(savedSelection) {
        if (savedSelection) {
            savedSelection.select();
        }
    };
}

使用示例:

var sel = saveSelection();
// Do stuff here
restoreSelection(sel);

这篇关于如何得到插入符合html子元素的contenteditable div中的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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