Possible to populate and save text entered from inside a iframe in designMode?

后端 未结 1 456

i am just about to start writing my own rich text editor but need to know if its possible to populate the text area and also how to save / use the data inside it.

I am c

1条回答
  •  难免孤独
    2021-01-27 04:47

    DEMO

    To let you start from somewhere, Here's your HTML:

    B I

    The all the basic JS/jQ you need is:

    $(function() {
    
      var $editor = $('#textEditor').prop('contenteditable', true);
      var $btn = $('span[data-cmd]');
    
      // EXECUTE COMMAND
      function execCmd(cmd, arg){      
        document.execCommand(cmd,false,arg);
      }
    
      $btn.mousedown(function(e) {
        e.preventDefault();
        $(this).toggleClass("selected");
        execCmd(this.dataset.cmd);
      });
    
      $("#fonts").change(function() {
        execCmd("FontName", this.value);       
      });
    
    });
    

    AND HERE'S A jsBin DEMO

    Now, I've seen that you want, on button click make it state ACTIVE, but if you think twice what you'll achieve is a mess for one reason:

    User enters text -> selects a portion and clicks BOLD, now it jumps with the cursot to the beginning of line where there's no BOLD text... but wait, your button still has the active state...

    to prevent such UX, you need to keep track of the child element the user has selected, and accordingly turn ON all the buttons from your options tab that match the selected tag criteria.

    I won't let you down so here's an example:

    $(function() {
    
      var $editor = $('#textEditor').prop('contenteditable', true);
      var $btn = $('span[data-cmd]');
      var tag2cmd = {"B":'bold', "I":'italic'};
    
      // HIGHLIGHT BUTTONS on content selection
      function findParentNode(el) {
    
        $btn.removeClass('selected');
    
        var tagsArr = [];
        var testObj = el.parentNode || '';
        if(!testObj){return;}
    
        var c = 1;
        tagsArr.push(el.nodeName);
        if(el.tagName!='DIV'){
            while(testObj.tagName != 'DIV') {
                c++;
                tagsArr.push(testObj.nodeName);
                testObj = testObj.parentNode;   
            }
            for(i=0;i

    AND IT'S DEMO

    So you see, only one 'idea' and the code gets immediately huge, so if you really want to keep it simple, avoid such stuff and have fun!

    0 讨论(0)
提交回复
热议问题