【问题标题】:Detect which letter from a word is clicked using javascript使用javascript检测单词中的哪个字母被点击
【发布时间】:2021-10-28 18:59:10
【问题描述】:

我注意到互联网上有不同的解决方案,其中描述了如何检测用户点击的word。但我想知道是否有解决方案来检测单词中的字母或用户点击的位置。例如:

<div>this is the text</div>

当用户点击控制台中的第一个字母时,应该输出t
是不是像我上面描述的那样使用 javascript 找到被点击的字母的解决方案?

【问题讨论】:

标签: javascript


【解决方案1】:

您可能可以使用Selection API 来检查光标的位置并提取最接近它的字母:

document.onclick = (evt) => {
  const sel = getSelection();
  if (sel.rangeCount) {
    const range = sel.getRangeAt(0);
    const targetedNode = range.startContainer;
    const clickedLetter = targetedNode.textContent.substr(range.startOffset, 1);
    console.log(clickedLetter);
  }
};
<div>this is the text</div>

但在很多极端情况下它很可能会失败。

【讨论】:

    【解决方案2】:

    使用Selection.focusOffset获取离光标点击焦点最近的字符位置。

    document.onclick = (event) => {
      const selection = getSelection();
      const charClicked = selection.focusNode.data[selection.focusOffset]
      if (charClicked) {
        console.log(charClicked);
      }
    };
    <div>this is the text</div>

    【讨论】:

      猜你喜欢
      • 2017-09-20
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 2016-02-08
      • 2018-07-09
      • 1970-01-01
      相关资源
      最近更新 更多