【问题标题】:Rangy move boundaries of user selection out of header elementRangy将用户选择的边界移出标题元素
【发布时间】:2012-09-12 03:34:49
【问题描述】:

我正在使用 rangy 并且有一个带有 contenteditable div 的案例,其中可以保存用户选择并稍后恢复,以便可以插入 HTML。

我的问题是,如果用户在标题元素中选择,我不希望将 html 插入标题中。

所以我试图弄清楚如何使用 rangy,以便如果在标题中进行选择,那么我可以将它移动到标题元素之前。

所以如果用户在 h1 内选择:

<div id="editable" contenteditable>
     <h1>|user selects here| Header Text</h1>
</div>

然后保存的选择将移动到 h1 之前:

| selection boundary moved here |<div id="editable" contenteditable>
     <h1>|user selects here| Header Text</h1>
</div>

我尝试了以下方法,看看是否可以移动选择边界:

var sel = rangy.getSelection();
var range = sel.getRangeAt(0);

range.setStartBefore(sel.anchorNode.parentNode);

sel.removeAllRanges();
sel.addRange(range);

selected = rangy.saveSelection();

但是当我在 H1 中选择时,它仍然在 H1 内而不是在它之前设置保存的选择边界。我不确定如何在标题元素之前移动边界。

【问题讨论】:

  • This is likely related to how the browser reports the selection, which varies between browsers, particularly when the selection boundary is at the edge of an element or text node.

标签: rangy


【解决方案1】:

我无法弄清楚如何使用 rangy 来执行此操作,最后最终使用 jQuery 处理了清理工作。不确定这是否是最好的方法,但它对我有用。基本上,我想删除任何可能放置在标题中的 div:

$('#cleanup').click(function(e){

        e.preventDefault();

        var header, clone;

        // loop through each header element
        $(#editor :header').each(function(){

            // assign header element to variable
            header = $(this);

            // go through the header's children
            $(header).children().each(function(){

                // if we have a div in the header,
                if( $(this).is("div")){ 

                    // clone it
                    clone = $(this).clone();

                    // put clone before the header
                    $(header).before(clone);

                    // remove the original from the header
                    $(this).remove();

                }

            });

        });

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多