[英]How to select certain text from a textarea element
您可以使用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 >
您可以使用它在文本區域內選擇所需的文本。 為了使選擇生效,您必須首先將重點放在文本區域上。
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.