问题
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