如何在div中选择事件?

时间:2012-02-15 14:49:23

标签: html contenteditable

<div id="container" style="border: 1px solid #333" contentEditable="true">Type text    here</div>

选择文字时是否有触发功能? (Type text here

3 个答案:

答案 0 :(得分:2)

您可以使用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>

答案 1 :(得分:0)

您可以使用onMouseUp事件并检查是否存在选择,如下例所示:
http://jsfiddle.net/2gLLp/

另见: http://www.codetoad.com/javascript_get_selected_text.asp

答案 2 :(得分:0)

我使用了选择更改事件,您可以尝试

    document.addEventListener('selectionchange', (e)=>{
        console.log("Archor node - ",window.getSelection().anchorNode.parentElement);
    });