简体   繁体   中英

Paste html from textarea to Contenteditable Div

I'm developing a RTE(rich text editor) using a wrapper div.

<div id="myeditor"></div>
//then
editorfunction(myeditor);
What the function does is add the following elements
<div id="myeditor">
    <div class="toolbar">buttons here</div>
    <div class="editorwrapper">
      <div class="editor-richtext">
         rich text etc
      </div>
      <textarea class="editor-source"><p>rich text etc</p></textarea>
    </div>
</div>

I can successfully grab the html from the .editor-richtext and put it inside the textarea, but when I edit the textarea, I don't seem to be able to paste that back into the rich-text.

Thanks in advance!

Update 1
Ok, it seems that

$("richtext").blur(function() {
   $("textarea").val($(this).html());
});

Works fine, but not the other way around (from textarea to richtext).

Update 2 It seems it is very unstable, it partially works but is acting strange :\\ I'm not able to fully get content from textarea and paste as html into contenteditable. I will continue to do some research.

Update 3 I just updated update 1 and update 2 as I totally flipped textarea and richtext in my brain. Sorry!

Update 4 Ok, I pretty much got it solved now. I just have one slight problem, upon initialization, if I don't focus the contenteditable div and switch to the source view\\textarea. the textarea is emptied, and when I then go back to RTE view\\contenteditable div it is emptied. from the empty textarea\\source. I'm working on a work-around.

You can hook the onBlur event of textarea to copy the text and paste it in editor-richtext

$("textarea.editor-source").blur(function(){
   $("div.editor-richtext").html($(this).val());
});

EDIT

For other way around, you can use the following code segment

$("textarea.editor-source").focus(function(){
   $(this).val($("div.editor-richtext").text());
}); 

You may want to use jQuery and the following functionnalities?

$(".editor-source").keyup(function() {
    $(".editor-richtext").html($(this).val());
});

Everything works fine. Selectors in your example are incorrect thought:

HTML:

  <div class="editor-richtext">
     original text
  </div>

  <textarea class="editor-source">modified text</textarea>

JS:

  $(".editor-source").blur(function() {
     $(".editor-richtext").html($(this).val());
  });​

Demo

UPD:

$(".editor-richtext").click(function(){
    $(".editor-source").val($(this).html().trim());
});

new demo that puts content from div into textarea on click event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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