微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用编码字符正确选择偏移量

出于各种原因,我正在尝试在 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);
});

如果您选择“

你知道任何简单的解决方法吗?我知道我也许可以使用 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 = {
    '&': '&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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。