Adding <h1> around a selection

喜欢而已 提交于 2019-12-04 22:38:00

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:

  1. don't change start or end container; apply h1 as is
  2. set end to after focusNode parent
  3. set start to before anchorNode parent
  4. 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

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