簡體   English   中英

Microsoft Edge window.getSelection()返回不正確的結果

[英]Microsoft Edge window.getSelection() returns incorrect result

我在Microsoft Edge上遇到了這種情況; Chrome的行為符合預期。

問題在於,當選擇中包括最后一個字符時,使用Edge時,window.getSelection()。anchorOffset或window.getSelection()。focusOffset返回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>

您可以嘗試使用

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 API |中文 MDN

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

此外,如果要檢查瀏覽器是否為Edge,可以執行以下操作。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM