简体   繁体   English

如何在 JavaScript 中的文本区域中选择单词或短语?

[英]How to select a word or a phrase in a text area in JavaScript?

I am currently creating a text editor in HTML and JavaScript and I want to add a find function where you would type the word that you want to find then it will select the word.我目前正在用 HTML 和 JavaScript 创建一个文本编辑器,我想添加一个查找功能,您可以在其中键入要查找的单词,然后它会选择该单词。 Now what I mean by "select" here is that the script will select with the blue color around a word so that I could copy, cut, paste, delete.现在我在这里所说的“选择”是指脚本将选择一个单词周围的蓝色,以便我可以复制、剪切、粘贴、删除。 Because I can't find a solution on the Internet, is there a way to do the thing I talk earlier in pure JavaScript?因为在网上找不到解决办法,有没有办法用纯JavaScript来做我之前讲的事情?

Example:例子: 查找功能

Rewrite of How to select line of text in textarea重写如何在 textarea 中选择文本行

http://jsfiddle.net/mplungjan/jc7fvt0b/ http://jsfiddle.net/mplungjan/jc7fvt0b/

Change the select to an input field to type yourself将选择更改为输入字段以自己输入

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM