Microsoft Edge window.getSelection()返回不正确的结果

时间:2018-04-27 08:50:57

标签: javascript microsoft-edge

我正在使用Microsoft Edge体验这一点; Chrome的行为符合预期。

问题是当最后一个字符包含在选择中时,window.getSelection()。anchorOffset或window.getSelection()。focusOffset在使用Edge时返回1。 (哪个函数返回值1取决于选择的方向。)参考下面的示例,我希望值为225 - 这是Chrome返回的值。当选择包括除最后一个字符以外的任何内容时,结果是正确的。任何关于变通方法或不同方法的指导都将受到赞赏。感谢。

<style>
    #mydiv {
        position: absolute;
        display: inline-block;
        border: 1px solid;
        top: 100px;
        left: 100px;
        width: 400px;
        height: 300px;
    }
</style>

<script>
    var mydiv = document.getElementById("mydiv");
    mydiv.addEventListener("dragstart", function (e) {
        e.preventDefault();
        var s = window.getSelection().anchorNode.textContent;
        var anchorOffset = window.getSelection().anchorOffset;
        var focusOffset = window.getSelection().focusOffset;
        myresults.textContent = "anchorOffset: " + anchorOffset + " focusOffset: " + focusOffset;
    });
    var myresults = document.getElementById("myresults");
</script>

<div id="mydiv" class="mydiv" contenteditable="true">Microsoft Edge: Select a portion of text here then drag it. The selection anchorOffset and focusOffset will display. Do it again, but this time make sure the last character is included in the selection. One of the values will be 1!</div>
<div id="myresults"></div>

1 个答案:

答案 0 :(得分:0)

您可以尝试使用

function getSelectedText() {
  var txt = '';

  if (window.getSelection) {
    txt = window.getSelection();
  }
  else if (document.getSelection) {
    txt = document.getSelection();
  }
  else if (document.selection) {
    txt = document.selection.createRange().text;
  }
  else return; 

  return txt;
}

此方法的浏览器兼容性如下所示。

参考:

DocumentOrShadowRoot.getSelection() - Web APIs | MDN

https://caniuse.com/#search=window.getSelection

此外,如果要检查浏览器是否为Edge,则可以执行以下操作。

window.navigator.userAgent.indexOf("Edge") > -1