返回博客

JS 文本选择监听

本文介绍如何使用 JavaScript 监听文本选择事件,并获取选中文本信息和位置。

Mt.r
|
document.addEventListener("selectionchange", () => {
  console.log(document.getSelection());
});

document.onselectionchange = () => {
  console.log(document.getSelection());
};
// document.getSelection() 选中文本信息,document.getSelection().toString() 则返回选中文本
const selection = document.getSelection()
const oRange = selection.getRangeAt(0)
const oRect = oRange.getBoundingClientRect()
const text = selection.toString()

转载