2017-08-14 62 views
0

我试图以务实的方式创建用户选择。 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> 

一切似乎是工作的罚款,我得到的预期输出到控制台,但是文本不会在屏幕上选择。它是否由设计?

回答

1

你已经找到了范围,但现在你需要告诉浏览器选择它。例如:

var sel = window.getSelection(); 
sel.removeAllRanges(); 
sel.addRange(range); 
+0

谢谢,这是失踪的位。我试图不通过'removeAllRanges'删除当前选择的范围,没有这个就不行。你知道为什么吗?看到[这个掠夺者](https://plnkr.co/edit/Ce0VcDZVwzHJguegZoyu?p=preview) - 选择屏幕上的东西,等待3秒 –

+0

我不认为浏览器通常支持多个选择范围(见[关于多个范围(http://help.dottoro.com/ljcpcpnt.php))。相反,你可以做的是获得现有的选择范围并修改它。要获得范围,请使用'var range = sel.getRangeAt(0);'。 – AntPhitlok

+0

这个[引用](https://developer.mozilla.org/en-US/docs/Web/API/Range)代表'Range'对象可以帮助你扩展/修改你的范围,然后你可以使用'removeAllRanges( )'和'addRange()'来做出结果选择。 – AntPhitlok

相关问题