在HTML中选择后持久保留范围对象的更改

在HTML中选择后持久保留范围对象的更改,第1张

在HTML中选择后持久保留范围对象的更改

对于每个选择,您可以将所选范围序列化为字符偏移量,并在重新加载时使用如下所示再次将其反序列化:

码:

var saveSelection, restoreSelection;if (window.getSelection && document.createRange) {    saveSelection = function(containerEl) {        var range = window.getSelection().getRangeAt(0);        var preSelectionRange = range.cloneRange();        preSelectionRange.selectNodeContents(containerEl);        preSelectionRange.setEnd(range.startContainer, range.startOffset);        var start = preSelectionRange.toString().length;        return { start: start, end: start + range.toString().length        };    };    restoreSelection = function(containerEl, savedSel) {        var charIndex = 0, range = document.createRange();        range.setStart(containerEl, 0);        range.collapse(true);        var nodeStack = [containerEl], node, foundStart = false, stop = false;        while (!stop && (node = nodeStack.pop())) { if (node.nodeType == 3) {     var nextCharIndex = charIndex + node.length;     if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {         range.setStart(node, savedSel.start - charIndex);         foundStart = true;     }     if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {         range.setEnd(node, savedSel.end - charIndex);         stop = true;     }     charIndex = nextCharIndex; } else {     var i = node.childNodes.length;     while (i--) {         nodeStack.push(node.childNodes[i]);     } }        }        var sel = window.getSelection();        sel.removeAllRanges();        sel.addRange(range);    }} else if (document.selection) {    saveSelection = function(containerEl) {        var selectedTextRange = document.selection.createRange();        var preSelectionTextRange = document.body.createTextRange();        preSelectionTextRange.moveToElementText(containerEl);        preSelectionTextRange.setEndPoint("EndToStart", selectedTextRange);        var start = preSelectionTextRange.text.length;        return { start: start, end: start + selectedTextRange.text.length        }    };    restoreSelection = function(containerEl, savedSel) {        var textRange = document.body.createTextRange();        textRange.moveToElementText(containerEl);        textRange.collapse(true);        textRange.moveEnd("character", savedSel.end);        textRange.moveStart("character", savedSel.start);        textRange.select();    };}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5060560.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存