如何从 onSelect DOM 事件中获取所选文本的文本值

mpu*_*aye 5 html javascript dom

认为这是一个简单的问题,但我对 Web 开发人员很陌生,所以我很抱歉 :) -> 在 onSelect 事件中,我如何获取所选内容的内容?有没有办法修改选中的文本,比如高亮显示?

这是我到目前为止:

<textarea id="text">
Text to be highlighted
</textarea>
Run Code Online (Sandbox Code Playgroud)

在js中:

let text_selection   = document.getElementById("text");
text_selection.addEventListener("select", highlightText);

function highlightText(){
  alert('hello');
}
Run Code Online (Sandbox Code Playgroud)

san*_*shi 2

获取您可以使用的选定文本textarea.selectionStart,如textarea.selectionEnd另一个答案中所述

要解决问题的第二部分,您将需要一些 CSS 规则来突出显示所选文本。请检查代码片段。

let text_selection = document.getElementById("text");
text_selection.addEventListener("select", highlightText);

function highlightText() {
  let textarea = event.target;
  let selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
  console.log(selection)
}
Run Code Online (Sandbox Code Playgroud)
::-moz-selection {
  color: yellow;
}

::selection {
  color: yellow;
}
Run Code Online (Sandbox Code Playgroud)
<textarea id="text">
Text to be highlighted
</textarea>
Run Code Online (Sandbox Code Playgroud)