简体   繁体   English

通过单击按钮将所选文本从一个内容div移动到另一个内容div

[英]Moving selected text from one content div to another content div by clicking a button

I would like to move the selected text from one content div to another content div. 我想将选定的文本从一个内容div移动到另一个内容div。 And the selected text should append at the current caret position of the other div. 并且所选文本应附加在另一个div的当前插入标记位置。 Is there any way to get care position based on div id ? 有什么方法可以根据div id获取护理位置吗? I observed in all the sources,the obtained caret position is always based on selection . 我在所有来源中都观察到,获得的插入符位置始终基于选择。

<body >
 <div contenteditable="false" id='selectfromhere' >
   some text select
  </div>
   <div contenteditable="true" id='movehere' >
   some
  </div>
  <button>Click me</button>
</body>

Try this: 尝试这个:

 var selectedText = ''; $(document).ready(function() { $('#selectfromhere').mouseup(function() { selectedText = window.getSelection().toString(); console.log(selectedText); }); $('button').click(function() { $('#selectfromhere').html($('#selectfromhere').html().split(selectedText).join("")); $('#movehere').append(selectedText); window.getSelection().removeAllRanges(); selectedText = ''; console.log('Some Text ' + selectedText); }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div contenteditable="false" id='selectfromhere'> some text select </div> <div contenteditable="true" id='movehere'> </div> <button type="button">Click me</button> </body> 

Hope it answered you question /Zorken17 希望它回答了您的问题/ Zorken17

Here is a solution for getting the caret position of a content-editable : Get caret position in contentEditable div 这是获取内容可编辑的插入符位置的解决方案: 在contentEditable div中获得插入符位置

If you use that function to get an integer value for caret position (var caretPosition), the following should insert your text: 如果使用该函数获取插入符号位置的整数值(var caretPosition),则以下内容应插入您的文本:

var insertText = $("#selectfromhere").html();
var currentText = $("#movehere").html();
var output = [currentText.slice(0, caretPosition), insertText, currentText.slice(caretPosition)].join('');

$("#movehere").html() = output;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM