问题
I have a jsfiddle here - http://jsfiddle.net/88em6qq9/ - where I'm trying to add <h1>
tags around a selection of the entire line: "Here is some content and here too"
Selecting the entire line and releasing the mouse button goes into the handler but rounding off the start and end end points with setStartBefore() and setEndAfter() gets me to different start and end containers, so the surround doesn't work.
If I put "Here is some content" in its own <span>
- see http://jsfiddle.net/88em6qq9/1/ - then we round to the same container and the h1
insert does work. But I need a solution that puts <h1>
tags around the selection whether the first phrase is in a span or not.
Thanks for any help.
<div id="container">
<div class="content" contenteditable="true">Here is some content<span class="red"> and here too</span></div>
</div>
回答1:
I hammered out a workable solution to this. The selected text range can be in one of four states when I start:
startContainer in a span endContainer in a span
no no
yes no
no yes
yes yes
And I'm able to surround each of these by an h1 by applying one of the four operations below:
- don't change start or end container; apply h1 as is
- set end to after focusNode parent
- set start to before anchorNode parent
- set end to after focusNode parent and set start to before anchorNode parent
So I go down through these four operations, applying each one to my range, and after each I see if canSurround() returns true. When it does I stop and do the surround.
The code is:
case "RTE_h1_icon" :
newNode = document.createElement("h1");
var sel = rangy.getSelection();
anchorParent = sel.anchorNode.parentNode;
focusParent = sel.focusNode.parentNode;
range = sel.getRangeAt(0);
if(range.canSurroundContents()) { // no modification
range.surroundContents(newNode);
break;
}
range1 = range;
range1.setEndAfter(focusParent); // adjust end
if(range1.canSurroundContents()) {
range1.surroundContents(newNode);
break;
}
range2 = range;
range2.setStartBefore(anchorParent); // adjust start
if(range2.canSurroundContents()) {
range2.surroundContents(newNode);
break;
}
range3 = range;
range3.setStartBefore(anchorParent); // adjust start
range3.setEndAfter(focusParent); // and end
if(range3.canSurroundContents()) {
range3.surroundContents(newNode);
break;
}
break;
If anyone has a better solution or sees problems with what I'm doing I'd be glad to hear from you.
Thanks
来源:https://stackoverflow.com/questions/25221555/adding-h1-around-a-selection