【问题标题】:Find the cursor targeted element id in contenteditable在 contenteditable 中查找光标目标元素 id
【发布时间】:2016-12-12 14:18:51
【问题描述】:

在 contenteditable div 中,我有不同的子元素 ID。 光标移动时在 contenteditable 标记内。我需要获取光标位置元素 ID。

像这样:例子

  1. 如果cursor 位置在one 字符串上,则输出是光标位置元素的ID,例如 1
  2. 如果是two 输出2

我尝试这样,但我没有找到光标目标子 ID。它只在父母身上。

function check(e){
  console.log($(e.target).attr('id'))
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable="true"   id="res" tabindex="2"  onkeydown="check(event)">solve:
<span id="1">one</span>
  <p id="2">two</p>
  <i id="3">three</i>
</div>

【问题讨论】:

    标签: javascript jquery html css cursor


    【解决方案1】:

    你可以这样做:

    $('#res').on('keyup', function() {
      var el = window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode;
      console.log(el.id);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div contentEditable="true" id="res" tabindex="2">solve:
      <span id="1" class='number'>one</span>
      <p id="2" class='number'>two</p>
      <i id="3" class='number'>three</i>
    </div>

    您可以在此link 阅读有关window.getSelection() 的信息。

    您可以在此link 阅读有关window.getSelection()getRangeAt() 结合使用的信息。

    【讨论】:

    • 它的鼠标移动不像只有keyevent那样
    • 你能提供一些该功能的参考链接
    • @prasad,是的,我可以。在我更新的答案中添加了一个链接。希望对您有所帮助。
    猜你喜欢
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 2015-01-16
    • 1970-01-01
    相关资源
    最近更新 更多