繁体   English   中英

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

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

我想获取文本区域内所选文本的 position。 这是必要的,以便在所选文本上方显示带有弹出窗口的 div。 在香草JS或angular(可能是指令)中是否有一些可以理解的简单方法来计算?

我需要坐标,用于设置绝对 position

这实际上很容易做到。

您可以从任何文本字段中获取选择开始和选择结束。 看看这个

它的工作方式如下:

 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>

如果您想获得 position,由于某种原因,它不适用于输入,但这也是它的代码。 它从选择范围中获取 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