4

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

4

3 回答 3

9

根据w3schools, onSelect 仅在 input 和 textarea 对象上定义。

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

于 2008-12-28T10:46:52.037 回答
5

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>
于 2012-02-15T15:09:38.197 回答
2

使用OnClick.

:select仅适用于某些表单元素。

于 2008-12-28T11:00:55.737 回答