使用rangy javascript library,,即使起始和结束位置没有相同的祖先,我们也可以按如下所示包围文本:
var range = rangy.createRangyRange();
range.setStart(firstNode, offsetFirstNode);
range.setEnd(lastNode, offsetSecondNode);
var rangyOptions = { useExistingElements: false };
var applier = rangy.createClassApplier('span', rangyOptions);
applier.applyToRange(range);
如何在Java org.w3c.dom(不是Javascript)中执行此操作? 我尝试如下操作,但是如果起点和终点没有共同的祖先,则失败。在此代码中,我们仅创建一个“ span”元素,但我们需要创建多个元素(Rangy会这样做):
import org.w3c.dom.ranges.*
Range range = doc.asInstanceOf[DocumentRange].createRange()
range.setStart(firstNode, offsetFirstNode);
range.setEnd(lastNode, offsetSecondNode);
Element span = doc.createElement("span")
range.surroundContents(span)
// Fails with Exception in thread "main" org.apache.xerces.dom.RangeExceptionImpl: BAD_BOUNDARYPOINTS_ERR: The boundary-points of a Range do not meet specific requirements.