0
我正在使用提供按鈕來選擇文本而不是鼠標單擊和拖動的用戶界面。用戶得到一個文本框selection
輸入將被選擇的文本,和一組按鈕:如何在JavaScript中向後擴展選擇?
- 用於使選擇
- 延伸選擇到下一個字
- 延伸選擇到前一個字
該代碼完美適用於上面的前兩個任務。向後擴展選擇正在工作,但不是我想要的方式。
期望的功能:
通道:這是一個例子。在這段文字中輸入一些文字到下面的輸入框,然後按選擇按鈕選擇它。
選擇:從這個
擴展選擇向後:(目前)從
擴展選擇向後:(應選擇)從此
文本即我想向後移動anchor
一個字。我該如何實現它。
getSelectionText = function() {
sentence = document.getElementById("sentence");
target = document.getElementById("target");
selection = window.getSelection();
range = document.createRange();
index = sentence.innerHTML.indexOf(target.value);
range.setStart(sentence.firstChild, index);
range.setEnd(sentence.firstChild, (index + target.value.length));
selection.removeAllRanges();
selection.addRange(range);
}
removeSelection = function() {
selection = window.getSelection();
selection.removeAllRanges();
}
extendSelection = function(buttonId) {
var element = document.getElementById(buttonId);
if (element.id == "Previous") {
var selection = window.getSelection();
selection.modify("extend", "left", "word");
} else if (element.id == "Next") {
var selection = window.getSelection();
selection.modify("extend", "right", "word");
}
}
<body>
<div id="sentence">This is an example. Enter some text from this passage to the input box below and then press the select button to select it.
</div>
</br>
<b> Selection: </b>
<input type="text" id="target" value="an example" />
<br>
<br>
<input type="button" value="Select" onclick="getSelectionText()">
<button type="button" value="Remove Selection" onclick="removeSelection()"> Remove Selection</button>
<button type="button" id="Previous" onclick="extendSelection('Previous')">Extend Selection
< Previous</button>
<button type="button" id="Next" onclick="extendSelection('Next')">Extend Selection > Next</button>