How to parse editable DIV's text with browser compatibility

后端 未结 3 444
孤街浪徒
孤街浪徒 2021-01-14 07:33

I make div as editable. while i tried to parse div\'s text, i was needed to do the below regular expression.

innerDOM = \"
相关标签:
3条回答
  • 2021-01-14 07:47

    DOM manipulation is one of the things jQuery was made for. Investing in learning jQuery will take you a long way towards writing DOM traversal and modification.

    $("div[style='cursor: text']").unwrap().prepend("<br>");
    

    unwrap deletes the element but keeps the children intact. The jQuery Attribute Equals Selector is used to select all divs with the cursor style attribute. You can run it live here.

    You could make this more robust as currently you would not select a div with more or less whitespace or with other trivial differences. For example: <div style="cursor:text;"> is not matched by the above selector. You can work around this shortcoming by introducing a CSS class that sets the cursor. In this case <div style="cursor: text"> becomes <div class='textCursor'> and you can use the class selector: $("div.textCursor")

    0 讨论(0)
  • 2021-01-14 07:55

    i found this solution in this site:

    $editables = $('[contenteditable=true'];
    
    $editables.filter("p,span").on('keypress',function(e){
     if(e.keyCode==13){ //enter && shift
    
      e.preventDefault(); //Prevent default browser behavior
      if (window.getSelection) {
          var selection = window.getSelection(),
              range = selection.getRangeAt(0),
              br = document.createElement("br"),
              textNode = document.createTextNode($("<div>&nbsp;</div>").text()); //Passing " " directly will not end up being shown correctly
          range.deleteContents();//required or not?
          range.insertNode(br);
          range.collapse(false);
          range.insertNode(textNode);
          range.selectNodeContents(textNode);
    
          selection.removeAllRanges();
          selection.addRange(range);
          return false;
      }
    
       }
    });
    
    0 讨论(0)
  • 2021-01-14 07:59
    //FINAL ANSWER
    var domString = "", temp = "";
    
    $("#div-editable div").each(function()
                {
                    temp = $(this).html();
                    domString += "<br>" + ((temp == "<br>") ? "" : temp);
                });
    
    alert(domString);
    

    see this fiddle for answer.

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