Onselect事件不会触发div

dpq*_*dpq 3 html onselect

我无法触发附加到<div>元素的onselect事件处理程序.是否可以强制<div>发出选择事件?

dev*_*vio 9

根据w3schools,onSelect仅在输入和textarea对象上定义.

但是,您可以尝试捕获MouseUp事件检索当前窗口/文档中的选定文本.


Fah*_*kar 6

您可以使用onMouseUp事件来实现您想要的效果.见下文...

<html>
    <body>
        <div id="container" style="border: 1px solid #333" contentEditable="true" onMouseUp="checkMe()">Type text    here</div>

    </body>
    <script language="javascript">
    function checkMe() {
        var txt = "";

        if (window.getSelection) {
                txt = window.getSelection();
        }
        else if (document.getSelection) {
            txt = document.getSelection();
        } else if (document.selection) {
            txt = document.selection.createRange().text;
        }

        alert("Selected text is " + txt);
    }
    </script>
</html>
Run Code Online (Sandbox Code Playgroud)