[英]How to select certain text from a textarea element
I'm trying to select some text from a textarea element using javascript. 我正在尝试使用javascript从textarea元素中选择一些文本。 For example, I that this text in a textarea element "Today is the first day of the week" the user click a button to select the work "Today" so they can change it for any text.
例如,我认为该文本在textarea元素“今天是一周的第一天”中,用户单击按钮以选择工作“今天”,以便他们可以针对任何文本进行更改。
I konw that by doing element.select() I can select the entire content of the textarea, Is there another function or code that I can use to select only a work or a number or character within a textarea? 我知道通过执行element.select()可以选择文本区域的全部内容,是否有另一个函数或代码可以用来仅选择文本区域内的作品,数字或字符?
You can use selectionStart
and selectionEnd
here is simple sample on click it will select text based on where you clicked 您可以使用
selectionStart
和selectionEnd
这是单击的简单示例,它将根据您单击的位置选择文本
document.getElementById('text').addEventListener('click', function() { var length = this.value.length; this.setSelectionRange(this.selectionStart, length); }, false);
<textarea id="text" value="" size="20" >EXAMPLE</textarea >
You can use this to select the desired text inside of a textarea. 您可以使用它在文本区域内选择所需的文本。 For the selection to work, you have to set focus on the textarea first.
为了使选择生效,您必须首先将重点放在文本区域上。
var $_ = function(selector){ return document.querySelector(selector); } function selectText(str) { var txt = $_("#txt"); var idx = txt.value.indexOf(str); txt.focus(); txt.setSelectionRange(idx, idx + str.length); } $_("#btnSelect").addEventListener('click', function() { selectText($_("#selectWord").value); });
<textarea name="" id="txt" cols="30" rows="10">Today is gonna be the day that they're gonna throw it back to you.</textarea> <br><br> <input type="text" id="selectWord" value="gonna" /> <button id="btnSelect">Select</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.