为什么用户选择会呈现在屏幕上?
Why user selection is rendered on the screen?
我正在尝试务实地创建用户选择。 Here is the plunker。这是简单的设置:
<p>Tim O'Reilly calls for a Blogger Code of Conduct. His proposals are:</p>
<ol>
<li>Take responsibility not just for your own words, but for the
comments you allow on your blog.</li>
<li>Label your tolerance level for abusive comments.</li>
<li>Consider eliminating anonymous comments.</li>
</ol>
<script>
var range = document.createRange();
var startPar = document.querySelector('p').firstChild;
var endLi = document.querySelector('li:nth-child(2)').firstChild;
range.setStart(startPar,13);
range.setEnd(endLi,17);
console.log(range.toString());
</script>
一切似乎都工作正常,我得到了控制台的预期输出,但是屏幕上的文本没有被选中。是设计使然吗?
您已经找到范围,但现在您需要告诉浏览器select它。示例:
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
我正在尝试务实地创建用户选择。 Here is the plunker。这是简单的设置:
<p>Tim O'Reilly calls for a Blogger Code of Conduct. His proposals are:</p>
<ol>
<li>Take responsibility not just for your own words, but for the
comments you allow on your blog.</li>
<li>Label your tolerance level for abusive comments.</li>
<li>Consider eliminating anonymous comments.</li>
</ol>
<script>
var range = document.createRange();
var startPar = document.querySelector('p').firstChild;
var endLi = document.querySelector('li:nth-child(2)').firstChild;
range.setStart(startPar,13);
range.setEnd(endLi,17);
console.log(range.toString());
</script>
一切似乎都工作正常,我得到了控制台的预期输出,但是屏幕上的文本没有被选中。是设计使然吗?
您已经找到范围,但现在您需要告诉浏览器select它。示例:
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);