简体   繁体   中英

How to click on an element, move the mouse over other elements and then select those elements that you hovered over with JavaScript?

I am basically trying to replicate the .selectable() method of jQuery but I need it in vanilla JavaScript . Which event listener method should I use? I've tried with mousedown , but how can I detect that another element has been visited? Here is an example on how jQuery does it: [http://jsfiddle.net/ZfevM/99/]

I was able to figure it out. Had to work with mouseup and mousemove as well. Here is what I came up with and it works as expected: [https://repl.it/repls/EquatorialLumberingInfinity]

Any thoughts or alternative solutions are welcomed!

You could make use of window.getSelection() and [selection].getRangeAt([index]);

document
  .getElementsByTagName('body')[0]
  .addEventListener('mouseup', 
     function(){ 
       const selection = window.getSelection(); 
       const range = selection.getRangeAt(0); 

       console.log( selection, range ) 
  })

Selection has.containsNode() function to compare against given set; Range has.startContainer and.endContainer along with.commonAncestorContainer to compare against given structure

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