我正在使用JavaScript使用window.getSelection()
函数检索文本的所选部分的开头和结尾字符。
我正在Mac上使用Google Chrome 70。
当文本的长度超过65536(2 ^ 16)时,我遇到了以下问题:如果我选择一个单词,比如说以65533开始的10个字符,则起点是可以的(即65533),但结尾是点对应于实际位置减去65536(65543-65536 = 7)。
似乎浏览器正在将长文本分成65536个字符(64KB?)的块,而函数window.getSelection()
在其中却不知道所选内容的实际位置。
如果描述不清楚,请尝试所附的代码段:)
一种解决方案是,当小于开始部分时将65536添加到选择的结束部分,但是仅当跨第一和第二文本块并且仅当我从左向右选择时才有效。我需要保留与所选字符的实际位置相对应的数字,以实现我的目标。
非常感谢所有愿意帮助<3
的人
// A text of 783 characters get repeated untill it reaches 4 times the amount of 65536 characters
// then it is inserted into the div #text-box
let myText = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla imperdiet dignissim finibus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean vitae mauris dolor. Pellentesque eu turpis eu magna interdum pretium. Praesent ligula risus, interdum nec nunc vitae, imperdiet commodo nibh. Phasellus ac dolor at magna pretium tincidunt. Pellentesque sagittis finibus mi, at gravida elit pulvinar at. Proin malesuada justo laoreet nisi fermentum tincidunt. Sed tincidunt commodo sapien, quis fermentum velit suscipit volutpat. Ut sit amet ligula convallis, auctor eros a, finibus justo. Curabitur non eros malesuada, dignissim arcu vel, tincidunt augue. Aenean vitae accumsan turpis, id accumsan augue. Ut a massa ac neque interdum tempus.`;
let newText = '';
for (var i = 0; i<335; i++) {
newText += myText;
}
document.getElementById('text-box').innerHTML = newText;
// grab the selection
document.addEventListener('selectionchange', textSelection);
function textSelection() {
if (window.getSelection().focusNode.parentElement.id == 'text-box') {
let currentSelection = window.getSelection().toString();
let currentSelectionStart = window.getSelection().anchorOffset;
let currentSelectionEnd = window.getSelection().focusOffset;
document.getElementById('selection').innerHTML = currentSelection;
document.getElementById('start').innerHTML = currentSelectionStart;
document.getElementById('end').innerHTML = currentSelectionEnd;
}
}
#info-box {
background-color: #FEF9E7;
position: sticky;
position: -webkit-sticky;
top: 20px;
width: 30%;
}
<div id="info-box">
<h5>Selection starts at <span id="start">.</span></h5>
<h5>Selection ends at <span id="end">.</span></h5>
<h5>Text selected: <span id="selection">.</span></h5>
</div>
<div id="text-box">
</div>