简体   繁体   中英

How to get position of selected text in textarea?

I want to get the position of the selected text inside the textarea. This is necessary in order to show a div with a popup above the selected text. Is there some understandable simple way to calculate this either in vanilla JS or in angular (maybe directive)?

I need coordinates, for setting absolute position

This is pretty easy to do actually.

You can get the selection start and selection end from any textfield. Take a look at this .

It would work like the following:

 document.onselectionchange = function() { let inp = document.querySelector("input"); document.querySelector("p").innerText = "Start: "+inp.selectionStart+"\nEnd: "+inp.selectionEnd+"\n\nSelected: "+inp.value.substring(inp.selectionStart, inp.selectionEnd); }
 <!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <p></p> <input> </body> </html>

If you want to get the position, that doesn't work with inputs for some reason, but here's the code for that too. It grabs the boundingRect from the selection range.

 document.onselectionchange = function() { let inp = document.querySelector("div"); let sel = document.getSelection(); let bound = sel.getRangeAt(0).getBoundingClientRect(); document.querySelector("p").innerText = "Selected: "+inp.innerText.substring(sel.selectionStart, sel.selectionEnd)+"\n\nX: "+bound.left+"\nY: "+bound.top+"\n\nWidth: "+bound.width+"\nHeight: "+bound.height; }
 <:DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> <p></p> <div style="border: 1px solid black" contenteditable="true"> </body> </html>

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