问题描述
出于各种原因,我正在尝试在 js 中构建一个选择工具。 为了维护各种选择,它基于字符串中的索引/偏移量。 除非里面有一个编码的html字符,它被认为是一个字符,而不是4个。
示例:https://jsfiddle.net/1nLszqoa/
<div id="banner-message">
<p><Hello World</p>
</div>
document.addEventListener('mouseup',function() {
var selection = document.getSelection();
console.log(selection);
});
如果您选择“ 你知道任何简单的解决方法吗?我知道我也许可以使用 textarea 代替,但现在我正在追求这个领先。 谢谢
解决方法
你可以通过这个hack来计算偏移量:
在您提供的 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 = {
'&': '&','<': '<','>': '>','"': '"',"'": '''
};
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><Hello World</p>
</div>