简体   繁体   中英

How to get selected word when double-click on div, p, span?

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.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM