javascript - 如何从 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');
}
解决方案
您可以从事件目标中获取选择的开始和结束偏移量,并使用子字符串来确定选择
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
推荐阅读
- algorithm - 文件转换器一般如何工作,例如 word 到 pdf、XML 到 json、word 到 txt 等
- docker - 在 SWARM 中无法从工作节点访问服务
- django - 来自客户端的请求以数组形式出现,如何使用 Django REST 框架过滤器处理它
- build - 使用 --aot 的 Angular 构建失败并出现 'ɵbl'(导入为 'i1')未找到
- c - 在我的情况下,由 char (getc) 读取或由块读取 (fgets) 更有效的是什么
- python-3.x - 没有名为“nornir_utils”的模块
- python - 如何从终端运行 FastAPI?
- java - PDFBox:突出显示文本
- python - 如何查找列表中特定元组的元素总和?
- sql - 仓库活动记录总值