window.getSelection().toString()
详情:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getSelection
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>js 滑词分析</title>
</head>
<body>
<div id="selectText">文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本文本</div>
<script>
const getSelectText = () => {
try {
let text = window.getSelection().toString();
if (text != null && text != "") {
console.log(text);
}
} catch (err) {
let selecter = document.selection.createRange();
let text = selecter.text;
if (text != null && text != "") {
console.log(text)
}
}
};
window.onload = () => {
const selectText = document.querySelector('#selectText');
selectText.addEventListener('click', getSelectText, false);
}
</script>
</body>
</html>
来源:CSDN
作者:王海虎
链接:https://blog.csdn.net/xiaohu12685/article/details/104485542