getSelection在iOS 12中无法正常工作

时间:2018-10-12 01:17:48

标签: javascript ios

函数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;
}

enter image description here

1 个答案:

答案 0 :(得分:2)

我真的不知道为什么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>