【问题标题】:How to get the target element for an 'selectionchange' dom event如何获取“selectionchange”dom事件的目标元素
【发布时间】:2017-02-23 09:31:10
【问题描述】:

我发现自己处于想要获取触发 selectionChange dom 事件的目标元素的情况。

但是从https://developer.mozilla.org/en-US/docs/Web/Events/selectionchange来看,似乎e.target中的元素在正常(非输入,非文本区域)的情况下始终是文档对象。

这是否意味着我必须手动调用 window.getSelection,并找出当前光标位置并以这种方式找到 dom 节点?

有人知道捷径吗?或者一些工作示例会很好。

【问题讨论】:

    标签: javascript html dom-events


    【解决方案1】:

    如果您的元素可以成为活动元素,请使用document.activeElement 获取我们在其中选择的元素。这将适用于文本区域、输入和设置了tabindex 的元素。

    // NOTE: activeElement can only be found on selectable elements!
    
    document.addEventListener('selectionchange',function(){
    	document.getElementById('currentTag').innerHTML = document.activeElement.tagName;
    });
    #currentTag{
      font-weight:bold;
    }
    <textarea>This is sample text you can replace and move your cursor within. Whee!</textarea>
    
    <br><input type="text" placeholder="Input">
    
    <p tabindex="0">P tag text is the best tag text. <span color="blue">Unless you have a span.</span></p>
    
    <ol tabindex="0">
      <li tabindex="0">Item 1</li>
      <li tabindex="0">Item 2</li>
    </ol>
    
    <p id="currentTag"></p>

    【讨论】:

    • 嘿,嗯.. 感谢您回答我 3 年前提出的问题 XD 我应该选择一个答案..
    • 我认为此时对您来说为时已晚,但我正在寻找同样的东西并找到了这个问题。我想为其他来的人回答。 :) 感谢您接受我的回答。
    【解决方案2】:

    您可以使用document.selection 获取当前选择的内容。

    示例取自http://help.dottoro.com/ljixpxji.php

    <head>
        <script type="text/javascript">
            document.onselectionchange = OnChange;
            function OnChange () {
                var range = document.selection.createRange ();
                if (range.text.length == 0) {
                    alert ("The current selection is empty");
                }
                else {
                    alert ("The contents of the current selection are\n" + range.text);
                }
            }
        </script>
    </head>
    <body>
        Select this text on this page!
    </body>
    

    --编辑--

    正如@user1017674 所指出的,这段代码在chrome 中不起作用,经过一些研究,我发现document.selection 应该只在IE window.getSelection() 仍然是最好的获取途径。

    参考。 Does chrome supports document.selection?

    【讨论】:

    • 我不知道你是否在 chrome.F12 上尝试过这段代码并复制粘贴到控制台。 document.selection 一直给我未定义。有什么方法可以获取选中的dom节点吗?
    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 2011-01-28
    • 2018-10-25
    • 2017-07-09
    • 2020-08-22
    • 2020-03-31
    • 2020-09-29
    • 1970-01-01
    相关资源
    最近更新 更多