With Rangy, even though I extend the range by setStartBefore method, range.canSurroundContents method still returns false

北慕城南 提交于 2019-12-24 22:52:12

问题


I have the following 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:

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();
}
});

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

And also the following returns true:

range.containsNode(anchorNode);

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.

Thanks!


回答1:


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.

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

Code:

$('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);
    }
});


来源:https://stackoverflow.com/questions/13141992/with-rangy-even-though-i-extend-the-range-by-setstartbefore-method-range-cansu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!