扩展选择以包括AnchorNode和FocusNode的所有文本

问题描述

在这种情况下:用户选择一些文本。我想修改选择,以将完整的文本包含在边界AnchorNode和FocusNode中,而不考虑用户在哪里开始和停止选择。

<script>
    document.onselectionchange =(e)=>{
        let sel=document.getSelection();
        // Here I want to expand the selection to include all the text in the selection. For example
        // if "AA CC" is selected in the html below,I want to expand it to "AAAA BBBB CCCC"
    }
</script>




<span id="container" contenteditable="true">
    <span id="span1">AAAA </span><span id="span2">BBBB </span><span id="span3">CCCC </span><span id="span4">dddd</span>
</span>

这可能吗?任何指导将不胜感激。

解决方法

好的,我在这里看到了另一篇文章,这使我明白了秘密在于创建范围对象这一事实。这给了我我想要的东西:

    function onMouseUp(e) {
        let sel = document.getSelection();
        if (sel && sel.anchorNode && sel.anchorNode != document & sel.toString() != "") {
            let a = sel.anchorNode;
            let f = sel.focusNode;
            let r = document.createRange();
            r.setStartBefore(a);
            r.setEndAfter(f);
            sel.removeAllRanges();
            sel.addRange(r);
            console.log(sel.toString());
        }
    }
    window.addEventListener("mouseup",onMouseUp);