获取多个可编辑的div中的最新插入符号位置,并将图像附加到最后出现光标的div中

时间:2018-10-27 04:27:19

标签: javascript jquery dom contenteditable caret

我需要根据最近编辑过的事实在多个内容可编辑的div中添加图像。另外,contenteditable div本身包含HTML(不仅是文本),因此这些div中可能存在多个节点。要更正确地了解问题,请参见link to jsfiddle

$('#img-div').on('click',function(){
  //logic for appending according to latest caret position

  //if caret wasnt in any content editable div then do this
  $('#div-4').append($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col" id="img-div">
      <img src="https://creww.io/assets/images/creww-coin.png">
    </div>
    <div class="col">
       <div contenteditable="true" id="div-1">
          Div 1 here
       </div>
       <div contenteditable="true" id="div-2">
          Div 2 here
       </div>
       <div contenteditable="true" id="div-3">
          Div 3 here
       </div>
       <div contenteditable="true" id="div-4">
          Div 4 here
       </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

您可以参加最近的mouseover事件。

$('#img-div').on('click',function(){
 

  //if caret wasnt in any content editable div then do this
  lastDiv.append($(this).html());
  //$('#divApp').append(lastDiv.html());
 
});

 //logic for appending according to latest caret position
var lastDiv;
$('div[id*="div-"]').mouseover(function() {
lastDiv =$( this );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col" id="img-div">
      <img src="https://creww.io/assets/images/creww-coin.png">
    </div>
    <div class="col">
       <div contenteditable="true" id="div-1">
          Div 1 here
       </div>
       <div contenteditable="true" id="div-2">
          Div 2 here
       </div>
       <div contenteditable="true" id="div-3">
          Div 3 here
       </div>
       <div contenteditable="true" id="div-4">
          Div 4 here
       </div>
    </div>
    <div id="divApp"></div>
  </div>
</div>