js 获取如何鼠标滑词?

霸气de小男生 提交于 2020-02-24 22:58:52

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>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!