如何从textarea获取突出显示的文本位置? [英] How to get highlighted text position from textarea?
问题描述
我想使用javascript获取选定的文本位置.例如,
我有一个简单的文本区域.
I want to get the selected text position using javascript. For example,
I have a simple textarea.
#input-text {
resize: none;
width: 50%;
height: 50px;
margin: 1rem auto;
}
<textarea id="input-text">I am a student and I want to become a good person</textarea>
在我的文本区域中,我有一些文字,例如:
In my textarea, I have some text such as:
"I am a student and I want to become a good person"
从该字符串中,如果我从文本区域中选择成为好人",
然后,如何在javascript中获取选定的文本/字符串位置?
此处选定的字符串字符从29开始,以49结尾.因此,开始位置是29&.结束位置是49
From this string, if I select "become a good person" from the textarea,
Then How can I get the selected text/ string position in javascript?
Here the selected string character starts from 29 and ends in 49. So the start position is 29 & the end position is 49
推荐答案
这将适用于使用鼠标和键盘选择页面上所有<textarea>
元素的文本.
如果您不希望所有<textarea>
元素都具有此文本选择,请更改选择器(更具体).
This will work for text selection with the mouse and keyboard for all <textarea>
elements on the page.
Change the selector (be more specific) if you don't want all <textarea>
elements to have this text selection.
阅读注释,您会发现如果不想/不需要键盘选择,如何禁用键盘选择.
Read the comments, you will find out there how to disable keyboard selection, if you don't want/need keyboard selection.
var mySelection = function (element) {
let startPos = element.selectionStart;
let endPos = element.selectionEnd;
let selectedText = element.value.substring(startPos, endPos);
if(selectedText.length <= 0) {
return; // stop here if selection length is <= 0
}
// log the selection
console.log("startPos: " + startPos, " | endPos: " + endPos );
console.log("selectedText: " + selectedText);
};
var textAreaElements = document.querySelectorAll('textarea');
[...textAreaElements].forEach(function(element) {
// register "mouseup" event for the mouse
element.addEventListener('mouseup', function(){
mySelection(element)
});
// register "keyup" event for the keyboard
element.addEventListener('keyup', function( event ) {
// assuming we need CTRL, SHIFT or CMD key to select text
// only listen for those keyup events
if(event.keyCode == 16 || event.keyCode == 17 || event.metaKey) {
mySelection(element)
}
});
});
textarea {
resize: none;
width: 50%;
height: 50px;
margin: 1rem auto;
}
<textarea>I am a student and I want to become a good person</textarea>
这篇关于如何从textarea获取突出显示的文本位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!