简体   繁体   English

如何访问当前突出显示的文本<textarea>&lt;i&gt;in Javascript&lt;/div&gt;&lt;/i&gt;&lt;b&gt;在Javascript中&lt;/div&gt;&lt;/b&gt;</textarea><div id="text_translate"><p> 用户将在页面上的 HTML 文本区域中输入文本。 当他们突出显示该文本的一部分时,我如何访问突出显示的字符串? 突出显示 textarea 元素中的文本是否会触发任何事件?</p><p> 这是在文本区域是一个组件的反应应用程序的上下文中完成的。</p></div>

[英]How to access the currently highlighted text within a <textarea> in Javascript

The user will enter text into a HTML textarea on the page.用户将在页面上的 HTML 文本区域中输入文本。 When they highlight part of that text, how can I access the highlighted string?当他们突出显示该文本的一部分时,我如何访问突出显示的字符串? Are there any events triggered by highlighting of text in a textarea element?突出显示 textarea 元素中的文本是否会触发任何事件?

This is being done in the context of a react app where the textarea is a component.这是在文本区域是一个组件的反应应用程序的上下文中完成的。

Create a function that takes the value of your text area and gets the start and end using el.selectionStart and el.selectionEnd , then use el.substring() to get the selected text within the defined constraints for start and end .创建一个 function 获取文本区域的值并使用el.selectionStartel.selectionEnd获取开始和结束,然后使用el.substring()在定义的约束范围内获取所选文本startend

Lastly, run the function within an eventlistener that is listening to the text areas select event.最后,在监听文本区域select事件的事件监听器中运行 function。

 let textArea = document.getElementById('textArea') let display = document.getElementById('display') let getSelectedText = () => { let selectedText = textArea.value let selStart = textArea.selectionStart let selEnd = textArea.selectionEnd return selectedText.substring(selStart, selEnd) } textArea.addEventListener('select', () => { display.innerHTML = `<b>Your selected text is:</b> <i>${getSelectedText()}</i>` })
 <textarea id='textArea' rows="7" cols="50">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</textarea> <div id="display"></div>

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

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