函数document.getSelection()和window.getSelection()在iOS 12中不起作用。

该问题在Safari,Google Chrome和WKWebView中均出现。

在iOS 11和MacOS(任何版本)中,这些功能均有效。

你能建议吗?

Example:

document.querySelector("#contentjs").onclick = function () {
    console.log(document.getSelection());
    document.querySelector("#result").innerHTML = document.getSelection().anchorOffset;
}

javascript - getSelection在iOS 12中无法正常工作-LMLPHP

最佳答案

我真的不知道为什么document.getSelection()window.getSelection()在iOS 12中不起作用,但是当用户单击它时,下面的代码将返回节点内的偏移量。

var contentjs = document.querySelector('#contentjs');
contentjs.onclick = function (e) {
  var result = document.querySelector('#result');
  result.innerHTML = getAnchorOffset(e);
};

function getAnchorOffset (event) {
  var range;
  if (event.rangeParent && document.createRange) { // Firefox
    range = document.createRange();
    range.setStart(event.rangeParent, event.rangeOffset);
    range.setEnd(event.rangeParent, event.rangeOffset);
    return range.startOffset;
  } else if (document.caretRangeFromPoint) { // Webkit
    range = document.caretRangeFromPoint(event.clientX, event.clientY);
    return range.startOffset;
  } else if (document.caretPositionFromPoint) { // Firefox for events without rangeParent
    range = document.caretPositionFromPoint(event.clientX, event.clientY);
    return range.offset;
  }
  return 0;
}
<h4 id="result">anchorOffset</h4>
<div id="contentjs">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>

关于javascript - getSelection在iOS 12中无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52770900/

10-09 16:14