【问题标题】:How to select a word or a phrase in a text area in JavaScript?如何在 JavaScript 中选择文本区域中的单词或短语?
【发布时间】:2020-09-08 21:15:41
【问题描述】:
我目前正在用 HTML 和 JavaScript 创建一个文本编辑器,我想添加一个查找功能,您可以在其中键入要查找的单词,然后它将选择该单词。现在我所说的“选择”是指脚本将选择一个单词周围的蓝色,以便我可以复制、剪切、粘贴、删除。因为我在网上找不到解决办法,有没有办法用纯 JavaScript 做我之前说的事情?
示例:
【问题讨论】:
标签:
javascript
html
textarea
【解决方案1】:
重写How to select line of text in textarea
http://jsfiddle.net/mplungjan/jc7fvt0b/
将选择更改为输入字段以输入自己
function selectTextareaWord(tarea, word) {
const words = tarea.value.split(" ");
// calculate start/end
const startPos = tarea.value.indexOf(word),
endPos = startPos + word.length
if (typeof(tarea.selectionStart) != "undefined") {
tarea.focus();
tarea.selectionStart = startPos;
tarea.selectionEnd = endPos;
return true;
}
// IE
if (document.selection && document.selection.createRange) {
tarea.focus();
tarea.select();
var range = document.selection.createRange();
range.collapse(true);
range.moveEnd("character", endPos);
range.moveStart("character", startPos);
range.select();
return true;
}
return false;
}
/// debugging code
var sel = document.getElementById('wordSelector');
var tarea = document.getElementById('tarea');
sel.onchange = function() {
selectTextareaWord(tarea, this.value);
}
<select id='wordSelector'>
<option>- Select word -</option>
<option>first</option>
<option>second</option>
<option>third</option>
<option>fourth</option>
<option>fifth</option>
</select><br/>
<textarea id='tarea' cols='40' rows='5'>first second third fourth fifth</textarea>