本文介绍了使用Rangy,即使我通过setStartBefore方法扩展了范围,range.canSurroundContents方法仍然返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下html:

<p>Morbi quis augue vitae quam <a href="#">pharetra| varius</a> at at| urna.</p>

所选内容用|字符标记.以及所选内容的屏幕截图:

The selection is marked with | characters. Also a screenshot of the selection:

我可以扩展此选择以包含带有以下代码段的整个'a'元素(使用Rangy库 http://code.google.com/p/rangy/):

I can extend this selection to contain the whole 'a' element with the following code snippet (using Rangy library http://code.google.com/p/rangy/):

$('body').on('mouseup', '[contenteditable]', function() {
var block = this,
    sel = rangy.getSelection(),
    range = sel.getRangeAt(0);

if (sel.anchorNode.parentNode !== block) {
    range.setStartBefore(sel.anchorNode);
    sel.setSingleRange(range, false);
    sel.refresh();
}
});

要查看实际效果,请检查 http://jsfiddle.net/LTwkZ/1/

To see it in action, check http://jsfiddle.net/LTwkZ/1/

以下内容也返回true:

And also the following returns true:

range.containsNode(anchorNode);

问题是'range.canSurroundContents()'返回'false'.从头到尾,"a"元素完全包含在范围内,为什么不能使用"canSurroundContents()",如果可能的话,我该如何使用.

The problem is 'range.canSurroundContents()' returns 'false'. 'a' element is fully contained by range, from start to the end, why can not use 'canSurroundContents()' and how can I, if possible of course.

谢谢!

推荐答案

我认为问题是anchorNode是链接内的文本节点,而不是链接本身,因此选择是在链接内而不是之前开始的.将范围的开头移到链接之前应将其修复.另外,除非Rangy进行了其他修改,否则无需在选择中调用refresh(),尽管这不会引起任何问题.

I think the problem is that anchorNode is the text node within the link rather than the link itself, so the selection starts within the link rather than before it. Moving the start of the range before the link should fix it. Also, there is no need to call refresh() on the selection unless something other than Rangy has modified it, although that won't be causing any problems here.

修订的jsFiddle: http://jsfiddle.net/LTwkZ/2/

Revised jsFiddle: http://jsfiddle.net/LTwkZ/2/

代码:

$('body').on('mouseup', '[contenteditable]', function() {
    var block = this,
    sel = rangy.getSelection(),
    range = sel.getRangeAt(0);

    if (sel.anchorNode.parentNode !== block) {
        range.setStartBefore(sel.anchorNode.parentNode);
        sel.setSingleRange(range, false);
    }
});

这篇关于使用Rangy,即使我通过setStartBefore方法扩展了范围,range.canSurroundContents方法仍然返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 03:16