2017-08-14 65 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

相關問題