获取内容可编辑的插入符号位置 [英] Get contentEditable caret position

查看:0
本文介绍了获取内容可编辑的插入符号位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了大量关于如何contentEditable元素中设置插入符号位置的跨浏览器答案,但没有一个关于如何从获取插入符号位置的答案。

我想做的是知道keyup上的插入符号在div中的位置。因此,当用户输入文本时,我可以随时知道contentEditable元素中的插入符号位置。

<div id="contentBox" contentEditable="true"></div>

$('#contentbox').keyup(function() { 
    // ... ? 
});

推荐答案

以下代码假定:

  • 可编辑的<div>中始终有一个文本节点,没有其他节点
  • 可编辑div未将csswhite-space属性设置为pre

如果您需要一种更通用的方法来处理嵌套元素的内容,请尝试以下答案:

https://stackoverflow.com/a/4812022/96100

编码:

数据-lang="js"数据-隐藏="假"数据-控制台="假"数据-巴贝尔="假">
function getCaretPosition(editableDiv) {
  var caretPos = 0,
    sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      if (range.commonAncestorContainer.parentNode == editableDiv) {
        caretPos = range.endOffset;
      }
    }
  } else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    if (range.parentElement() == editableDiv) {
      var tempEl = document.createElement("span");
      editableDiv.insertBefore(tempEl, editableDiv.firstChild);
      var tempRange = range.duplicate();
      tempRange.moveToElementText(tempEl);
      tempRange.setEndPoint("EndToEnd", range);
      caretPos = tempRange.text.length;
    }
  }
  return caretPos;
}
#caretposition {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="contentbox" contenteditable="true">Click me and move cursor with keys or mouse</div>
<div id="caretposition">0</div>
<script>
  var update = function() {
    $('#caretposition').html(getCaretPosition(this));
  };
  $('#contentbox').on("mousedown mouseup keydown keyup", update);
</script>

这篇关于获取内容可编辑的插入符号位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆