![](/img/trans.png)
[英]how to get selected DOM using javascript if selected text is HTML?
[英]How to get text value of selected text from onSelect DOM event
认为这是一个简单的问题,但我对 Web 开发人员很陌生,所以我很抱歉 :) -> 在 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');
}
您可以从事件目标中获取选择的开始和结束偏移量,并使用子字符串计算出选择
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
要获取所选文本,您可以使用另一个答案中提到的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) }
::-moz-selection { color: yellow; } ::selection { color: yellow; }
<textarea id="text"> Text to be highlighted </textarea>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.