【问题标题】:How to select event in div?如何在div中选择事件?
【发布时间】:2012-02-15 14:49:22
【问题描述】:
<div id="container" style="border: 1px solid #333" contentEditable="true">Type text    here</div>

当我选择文本时是否有触发功能? (Type text here)

【问题讨论】:

标签: html contenteditable


【解决方案1】:

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

【讨论】:

  • 还有键盘选择和编辑和上下文菜单中的“全选”需要考虑。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    我已经使用了选择更改事件,你可以尝试一下

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 2011-04-07
      • 1970-01-01
      相关资源
      最近更新 更多