代码之家  ›  专栏  ›  技术社区  ›  x-rw

找到你写的节点

  •  0
  • x-rw  · 技术社区  · 6 年前

    我想得到写光标时光标所在的节点

    document.getElementById('parent').addEventListener('keypress', function(e) {
    
      console.log(e.target);
    });
    .root {
      padding-right: 1px;
    }
    
    #parent>div {
      border-color: yellow;
      float: left;
    }
    <div id="parent" contenteditable=true style="border: black 2px solid; height:200px">
      <div class="root" id="1">Qué</div>
      <div class="root" id="2">es</div>
      <div class="root" id="3">Lorem</div>
      <div class="root" id="4">Ipsum</div>
    </div>

    这个问题很复杂,因为我对每个单词都使用div。

    我需要使用div,这样你就可以用单词来显示建议(我正在做拼写检查)

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  3
  •   SimpleJ    6 年前

    你可以用 window.getSelection() 要获取光标下的实际节点:

    document.getElementById('parent').addEventListener('keydown', event => {
      const actualTarget = window.getSelection().anchorNode.parentNode;
      console.log(actualTarget);
    });
    .root {
      padding-right: 1px;
    }
    
    #parent>div {
      border-color: yellow;
      float: left;
    }
    <div id="parent" contenteditable="true" style="border: black 2px solid; height:200px">
      <div class="root" id="1">Qué</div>
      <div class="root" id="2">es</div>
      <div class="root" id="3">Lorem</div>
      <div class="root" id="4">Ipsum</div>
    </div>
        2
  •  1
  •   Facundo Larrosa    6 年前

    试试这个方法。我建议你用 弹起 事件以获取键入后的最后一个单词,从而生成建议列表:

    document.querySelectorAll('.root').forEach(function(el) {
    // Do stuff here
     el.onkeyup = function(e){
         console.log(e.target);
      };
    
    }); 
    .root {
      padding-right: 1px;
    }
    
    #parent>div {
      border-color: yellow;
      float: left;
    }
    <div id="parent" style="border: black 2px solid; height:200px">
      <div class="root" contenteditable="true" id="1">Qué</div>
      <div class="root" contenteditable="true" id="2">es</div>
      <div class="root" contenteditable="true" id="3">Lorem</div>
      <div class="root" contenteditable="true" id="4">Ipsum</div>
    </div>