Inserting a newline into a pre tag (IE, Javascript)

前端 未结 11 1879
走了就别回头了
走了就别回头了 2020-12-10 12:34

In IE when I insert text into a

 tag the newlines are ignored:





        
11条回答
  •  悲哀的现实
    2020-12-10 13:02

    I reckon this.

    What I found was IE is using \r\n and Fx(others) is using \n

    var newline;
    if ( document.all ) newline = '\r\n';
    else newline = '\n';
    
    var data = 'firstline' + newline + 'second line';
    document.getElementById("putItHere").appendChild(document.createTextNode(data));
    

    For a TinyMCE(wysiwyg editor) plugin I once made I ended up with using BR i edit mode and cleaned it up on submit etc.

    This code loops through all BR elements inside PRE elements and replaces BR with newlines.

    Note that the code relies on the TinyMCE API, but can easily be written using standard Javascript.

    Clean up:

            var br = ed.dom.select('pre br');
            for (var i = 0; i < br.length; i++) {
              var nlChar;
              if (tinymce.isIE)
                nlChar = '\r\n';
              else
                nlChar = '\n';
    
              var nl = ed.getDoc().createTextNode(nlChar);
              ed.dom.insertAfter(nl, br[i]);
              ed.dom.remove(br[i]);
            }
    

    Good luck!

提交回复
热议问题