【发布时间】:2018-04-10 16:01:16
【问题描述】:
我正在尝试使用 javascript 使用 Range.setStart 和 Range.setEnd 修改用户在 不可编辑 <div> 元素中选择的文本。具体来说,我希望用户能够单击一个句子并让我的代码将选择扩展到包含单击的句子,然后突出显示(并处理)它。
在 Chrome、Firefox 和 Edge 下,当我使用这些功能更改选择时,新的选择会在用户的浏览器窗口中突出显示。在 Mac High Sierra 下的 Safari 11 下,Range.* 函数正确地改变了选择范围,但用户的浏览器窗口没有改变以反映这一点。如果用户只是单击,则没有突出显示,或者如果用户单击并拖动初始突出显示保持不变。
到目前为止,我已经为 Mobile Safari 上的 <input> 字段找到了关于此问题的 SO 答案,例如
Programmatically selecting text in an input field on iOS devices (mobile Safari)
但不适用于桌面 Safari 上不可编辑的字段。
我将不胜感激任何提示、解决方法、错误报告或其他解决方案,谢谢。
Here is a JSBin demonstrating the problem.
这里是源代码。请注意,Safari 确实正确设置了范围,但无法突出显示它,而 Chrome、Firefox 和 Edge 使用新范围突出显示轨道:
function expandHL (){
let textSel = window.getSelection();
let newRange = textSel.getRangeAt(0);
let node = textSel.anchorNode;
console.log("Initial selection: " + newRange.toString().trim());
// Find and include start of sentence containing clicked region:
while (newRange.startOffset !== 0) { // start of node
newRange.setStart(node, newRange.startOffset - 1); // back up 1 char
if (newRange.toString().search(/^[.!?:\n]\s*/) === 0) { // start of sentence
newRange.setStart(node, newRange.startOffset + 1); // move forward char
break;
}
}
console.log("Final selection: " + newRange.toString().trim());
}
<h3>Demo of Safari highlighting problem.</h3>
<h4>
1. Click in the text below: the range is detected
and expanded (see console output). But it is
not highlighted as with Chrome or Firefox.<br><br>
2. Click and drag on the text below: your initial range
is highlighted, then expanded but highlighting does not expand
with range as with Chrome or Firefox. WHY?</h4>
<hr>
<div onclick="expandHL()">
Sed ut perspiciatis unde omnis iste natus error sit voluptatem
accusantium doloremque laudantium, totam rem aperiam, eaque
ipsa quae ab illo inventore veritatis et quasi architecto beatae
vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit
aspernatur aut odit aut fugit, sed quia consequuntur magni
</div>
【问题讨论】:
标签: javascript html safari range