使用编码字符更正选择偏移量



出于各种原因,我正在尝试用js构建一个选择工具。为了维护各种选择,它基于字符串中的索引/偏移量。除了如果其中有一个编码的html字符,它被认为是一个字符,而不是4个。

示例:https://jsfiddle.net/1nLszqoa/

<div id="banner-message">
<p>&lt;Hello World</p>
</div>
document.addEventListener('mouseup', function() {
var selection = document.getSelection();

console.log(selection);
});

如果选择"<H〃;,focusOffset(控制台中(将为2。除了Html,它是5。

你知道什么简单的解决方法吗?我知道我也许可以用一个文本区来代替,但现在我正在寻找这个线索。

谢谢

您可以执行此破解来计算偏移量:

在您提供的jsfiddle中,它的工作速度快于堆栈溢出代码片段工具。

document.addEventListener('mouseup', function() {
var selection = document.getSelection();

//get the text from start to focusOffset
var text = selection.anchorNode.nodeValue.substring(0, selection.focusOffset);
//you can do the excape with jquery like this
//this came from this link: https://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery
//var escaped = $("<div>").text(text).html();

//or only javascript like this 
var escaped = escapeHtml(text);

console.log(selection);
console.log(selection.anchorNode.nodeValue.substring(0, selection.focusOffset));
console.log('focusOffset: ' + selection.focusOffset);
console.log(escaped);
console.log('focusOffset hacked: ' + escaped.length);

});

//this came from this link: https://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript
function escapeHtml(text) {
var map = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
};

return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>&lt;Hello World</p>
</div>

最新更新