首页 > 解决方案 > 如何从 onSelect DOM 事件中获取所选文本的文本值

问题描述

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

这是我到目前为止所拥有的:

<textarea id="text">
Text to be highlighted
</textarea>

在js中:

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

function highlightText(){
  alert('hello');
}

标签: javascripthtmldom

解决方案


您可以从事件目标中获取选择的开始和结束偏移量,并使用子字符串来确定选择

text_selection.addEventListener("select", highlightText);

function highlightText(event){
    let textarea = event.target;
    let selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
    alert(selection)
    // ^^ don't use alert
    console.log(selection); 
}

https://developer.mozilla.org/en-US/docs/Web/API/Element/select_event


推荐阅读