双击div、p、span时如何获取选中的单词?

发布于 2024-08-22 02:02:05 字数 117 浏览 6 评论 0 原文

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

Can you get the word the user has double-clicked on? I've tried in a onDblClick eventhandler but selectionStart is undefined there; and the onselect event seems to be available only for TextArea.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌路终见情 2024-08-29 02:02:05

您可以在 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()

You can use document.selection.createRange().text in IE, and window.getSelection().toString() in firefox and webkit, and attach to the ondblclick handler like so:

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

References:

  • MSDN, for document.selection
  • MDN, for window.getSelection()
不弃不离 2024-08-29 02:02:05

@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>

A Good answer by @David Tang

and window.getSelection().toString() is what I used.


I want to share that you can use baseOffset and extentOffset too.

<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>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文