javascript - 根据鼠标在输入字段中的移动查找字符位置

标签 javascript html jquery css selection-api

我需要根据鼠标移动在输入字段中找到字符的位置

for example: if the input field has value as 'abcde' and I am moving my mouse on the character 'a' then the position will be 1, 'b' will provide 2 and so on for the other characters.

我确实找到了几个与 selectionStart 等一起使用的示例,但它们仅在插入符号放置在某个位置然后找到放置位置时才起作用。

我正在寻找的是 - 无论鼠标何时在字符上移动,输入字段中可能/可能不会完成点击 - 我能够知道鼠标悬停在字符上的位置。

我还不知道如何将鼠标坐标分别转换为字符位置。有没有这样的 javascript API?

非常感谢任何帮助/指示/想法。

更新

我的最终目标是在拖动发生在 contenteditable div 上时自动移动插入符号。我发现以下链接询问类似的问题 - 但到目前为止没有建议的解决方案。

caret auto move - https://stackoverflow.com/questions/12397792/update-caret-position-of-input-and-insert-text-on-drop-event/53660415#53660415

我还添加了另一个示例来展示原生拖动与 jQuery 拖动的不同行为。我正在使用不支持插入符号自动拖动的 jQuery 可拖动对象。

https://jsfiddle.net/VidushiGupta/7warczfy/

最佳答案

Jquery:您可以尝试 Caret plugin (虽然我不确定这是否满足您的需求)您可以阅读 jquery page ,但信息量不大!

Javascript 解决方案:

我四处寻找预先存在的解决方案,但关于悬停/鼠标悬停,我只找到了一个潜在的适应性解决方案。这段代码不是我的,它改编 self 由 Carlos Delgado 找到的一个公共(public) fiddle (我进行了改编,这样如果你将鼠标悬停在“显示位置”文本上,它将显示光标位置)。它还演示了 selectionStartselectionEnd 的使用,因此如果选择了文本,则会显示开始和结束位置。如果您使用箭头键向前或向后移动光标,然后再次悬停,则会显示更新后的光标位置。

此外,here's a shorter [alternative] version (without the start/end etc)

function getInputSelection(el) {
  var start = 0,
    end = 0,
    normalizedValue, range,
    textInputRange, len, endRange;

  if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
    start = el.selectionStart;
    end = el.selectionEnd;
  } else {
    range = document.selection.createRange();

    if (range && range.parentElement() == el) {
      len = el.value.length;
      normalizedValue = el.value.replace(/\r\n/g, "\n");

      // Create a working TextRange that lives only in the input
      textInputRange = el.createTextRange();
      textInputRange.moveToBookmark(range.getBookmark());

      // Check if the start and end of the selection are at the very end
      // of the input, since moveStart/moveEnd doesn't return what we want
      // in those cases
      endRange = el.createTextRange();
      endRange.collapse(false);

      if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
        start = end = len;
      } else {
        start = -textInputRange.moveStart("character", -len);
        start += normalizedValue.slice(0, start).split("\n").length - 1;

        if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
          end = len;
        } else {
          end = -textInputRange.moveEnd("character", -len);
          end += normalizedValue.slice(0, end).split("\n").length - 1;
        }
      }
    }
  }

  return {
    start: start,
    end: end
  };
}

document.getElementById("trigger").addEventListener("mouseover", function() {
  var input = document.getElementById("texto");
  var inputContent = input.value.length;
  // You may want to focus the textbox in case it's not
  input.focus();
  var result = getInputSelection(input);
  var resultSpan = document.getElementById("result");

  if (result.start == result.end) {
    resultSpan.innerHTML = "No text selected. Position of cursor is " + result.start + " of " + inputContent;
  } else {
    resultSpan.innerHTML = "You've selected text (" + result.start + " to " + result.end + ") from a total length of " + inputContent;
  }

}, false);
#trigger{background:#ff8890;}
<p>
  Get the cursor position in a textarea or a text input or the selected text.
</p><br>
<textarea id="texto"></textarea><br><br>
<input type="text" id="trigger" value="Show Position" size="10" /><br><br>
<span id="result"></span>

This solution也可以工作:它显示控制台中的位置(也许这是更可取的?)。如果需要,您可以进行调整。

document.getElementById('showpos').addEventListener('mouseenter', e => {
  console.log('Caret at: ', e.target.selectionStart)
})
<input id="showpos" />

希望这些想法对您有所帮助

雷切尔

关于javascript - 根据鼠标在输入字段中的移动查找字符位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53642519/

相关文章:

javascript - 上传和编辑图片 node.js 服务器

php - JSSOR 与皮肤上的 jQuery 单图像问题 thumbnail-navigator-07

c# - 生成的表与 rowspan 导致额外的单元格

php - javascript 空字段验证

javascript - 如何引用 PreloadJS 中预加载的图片

javascript - 控制台登录的对象长度为0但不为空

Javascript math.round 阈值

java - 获取 JTextPane 中选中文本的标签

javascript - Shopify.onItemAdded 更新#cart 和 cart.item.count

javascript - 是否有 jQuery 选择器/方法来查找特定的父元素 n 级?