【问题标题】:How to get selected word when double-click on div, p, span?双击div,p,span时如何获取选定的单词?
【发布时间】:2021-10-01 15:07:10
【问题描述】:

你能得到用户双击的单词吗?我在 onDblClick 事件处理程序中尝试过,但 selectionStart 在那里未定义;并且 onselect 事件似乎仅适用于 TextArea。

【问题讨论】:

  • 我能够做到这一点的唯一方法是将每个单词都包含在它自己的 SPAN 中。雅虎知道您右键单击时突出显示的单词。在 IE 中,加速器也知道突出显示的单词。这些是否连接到 javascript/DOM 层“下方”的浏览器,连接到某些 API?
  • 即在 Firefox 的上下文菜单中搜索 Yahoo Search。

标签: javascript selection html


【解决方案1】:

您可以在 IE 中使用 document.selection.createRange().text,在 firefox 和 webkit 中使用 window.getSelection().toString(),并像这样附加到 ondblclick 处理程序:

document.ondblclick = function () {
   var sel = (document.selection && document.selection.createRange().text) ||
             (window.getSelection && window.getSelection().toString());
   alert(sel);
};

参考文献

  • MSDN,为document.selection
  • MDN,为window.getSelection()

【讨论】:

    【解决方案2】:

    A Good answer by @David Tang

    window.getSelection().toString()是我使用的。


    我想分享你也可以使用baseOffsetextentOffset

    <p>test data.</p>
    
    <script>
      document.addEventListener("dblclick", (e)=>{
        const selection = document.getSelection()
        // console.log(selection.anchorNode.data) // is whole text: "test data."
        const selectContent = selection.anchorNode.data.slice(selection.baseOffset, selection.extentOffset)
        console.log(selectContent)    
      })
    </script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 2018-03-18
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多