【问题标题】:How to get position of selected text in textarea?如何在textarea中获取所选文本的位置?
【发布时间】:2022-01-23 01:30:11
【问题描述】:

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

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

【问题讨论】:

标签: javascript angular


【解决方案1】:

其实这很容易做到。

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

它的工作原理如下:

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>

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

【讨论】:

  • 未输入。在文本区域!
  • 它们的工作方式相同
  • 那么如何制作textarea。来自 contenteditable div?
猜你喜欢
  • 1970-01-01
  • 2020-06-07
  • 2013-03-19
  • 2010-10-17
  • 2014-10-20
  • 2012-08-25
  • 1970-01-01
  • 2019-12-12
  • 2011-07-07
相关资源
最近更新 更多