简体   繁体   English

如何从textarea获取突出显示的文本位置?

[英]How to get highlighted text position from textarea?

I want to get the selected text position using javascript.我想使用 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:在我的 textarea 中,我有一些文本,例如:

"I am a student and I want to become a good person"

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?那么如何在javascript中获取选定的文本/字符串位置?


Here the selected string character starts from 29 and ends in 49. So the start position is 29 & the end position is 49这里选择的字符串字符从 29 开始,到 49 结束。所以开始位置是 29 & 结束位置是 49

This will work for text selection with the mouse and keyboard for all <textarea> elements on the page.这将适用于使用鼠标和键盘为页面上的所有<textarea>元素选择<textarea> Change the selector (be more specific) if you don't want all <textarea> elements to have this text selection.如果您不希望所有<textarea>元素都具有此文本选​​择,请更改选择器(更具体)。

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>

I would make use of of onselect event to get the same.我会利用onselect事件来获得相同的结果。

<textarea id="input-text" onselect="myFunction(event)">I am a student and I want to become a good person</textarea>


<script>
    function myFunction(event) {
      const start  = event.currentTarget.selectionStart;
      const end= event.currentTarget.selectionEnd;
    }
</script>

Caramba answer worked pretty great, however I had the issue that if you selected some text and released the mouse outside of the textarea, the event didn't fire. Caramba 的回答非常有效,但是我遇到的问题是,如果您选择了一些文本并在 textarea之外释放鼠标,则该事件不会触发。

To solve this i changed the initial event to mousedown , this event registers a mouseup event on the document to ensure it fires after the cursor is released.为了解决这个问题,我将初始事件更改为mousedown ,此事件在文档上注册mouseup事件以确保在释放光标后触发。 The mouseup event then removes itself after it has fired. mouseup事件会在触发后自行移除。

This can be achieved with adding the once option to addEventListener , but sadly isn't supported in IE11 which is why i used the solution in the snippet.这可以通过向addEventListener添加once选项来实现,但遗憾的是 IE11 不支持,这就是我在代码段中使用解决方案的原因。

 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); }; function addSelfDestructiveEventListener (element, eventType, callback) { let handler = () => { callback(); element.removeEventListener(eventType, handler); }; element.addEventListener(eventType, handler); }; var textAreaElements = document.querySelectorAll('textarea'); [...textAreaElements].forEach(function(element) { // register "mouseup" event for those element.addEventListener('mousedown', function(){ // This will only run the event once and then remove itself addSelfDestructiveEventListener(document, '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>

    var idoftextarea='answer';
    function getSelectedText(idoftextarea){
        var textArea = document.getElementById(idoftextarea);
        var text =textArea.value;
        var indexStart=textArea.selectionStart;
        var indexEnd=textArea.selectionEnd;
        alert(text.substring(indexStart, indexEnd));

    }


    getSelectedText(idoftextarea);


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)
    }
});});

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

相关问题 如何从文本区域中突出显示的文本中获取邻居字符? - How to get neighbor character from highlighted text in the textarea? 如何在另一个文本区域中显示文本区域和可编辑 div 中突出显示的文本的 position? - How to show the position of highlighted text in a textarea and editable div, in a another textarea? 如何将突出显示的文本从textarea提交到数据库 - how to submit highlighted text from textarea into database 从div获取突出显示的文本并复制到textarea javascript中 - Get highlighted text from div and copy into textarea javascript 如何在 textarea(坐标)angular 中获取高亮显示的文本? - How to get postition highlighted text in textarea (coords) angular? 如何在textarea中获取所选文本的position? - How to get position of selected text in textarea? 如何使用 JavaScript 从网页中获取突出显示的文本 - How to get highlighted text from webpage with JavaScript 获取.html()和.text()中突出显示的文本位置 - Get the highlighted text position in .html() and .text() 在文本区域中显示突出显示的文本 - Displaying highlighted text in textarea 如何让 textarea 的 cursor 在拖放时移动到突出显示的文本的末尾? - How to get textarea's cursor move to the end of the highlighted text on drag and drop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM