简体   繁体   English

如何在textarea中获取所选文本的position?

[英]How to get position of selected text in textarea?

I want to get the position of the selected text inside the textarea.我想获取文本区域内所选文本的 position。 This is necessary in order to show a div with a popup above the selected text.这是必要的,以便在所选文本上方显示带有弹出窗口的 div。 Is there some understandable simple way to calculate this either in vanilla JS or in angular (maybe directive)?在香草JS或angular(可能是指令)中是否有一些可以理解的简单方法来计算?

I need coordinates, for setting absolute position我需要坐标,用于设置绝对 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.如果您想获得 position,由于某种原因,它不适用于输入,但这也是它的代码。 It grabs the boundingRect from the selection range.它从选择范围中获取 boundingRect。

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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