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

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

In IE when I insert text into a

 tag the newlines are ignored:





        
相关标签:
11条回答
  • 2020-12-10 13:01

    Here is a very small tweak to Edward Wilde's answer that preserves the attributes on the <pre> tag.

    if (elem.tagName == "PRE" && "outerHTML" in elem) {
        var outer = elem.outerHTML;
        elem.outerHTML = outer.substring(0, outer.indexOf('>') + 1) + str + "</PRE>";
    }
    else {
        elem.innerHTML = str;
    }
    
    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-12-10 13:03

    If you don't want to use outerHTML, you can also do the following for IE, if an additional pre tag is not an issue:

     if(isIE)
         document.getElementById("putItHere").innerHTML = "<pre>" + content+"</pre>";
     else
         document.getElementById("putItHere").innerHTML = content;
    
    0 讨论(0)
  • 2020-12-10 13:04
    if (typeof div2.innerText == 'undefined')
        div2.innerHTML = value;
    else
        div2.innerText = value;
    

    that worked for me.

    0 讨论(0)
  • 2020-12-10 13:08

    IE9 does not normalize white spaces, unlike its predecessors.

    You should test for support rather than targeting any specific browser. E.g...

    var t = document.createElement(elem.tagName);
    t.innerHTML = "\n";
    
    if( t.innerHTML === "\n" ){
        elem.innerHTML = str;
    }
    else if("outerHTML" in elem)
    {
        elem.outerHTML = "<"+elem.tagName+">" + str + "</"+elem.tagName+">";
    }
    else {
        // fallback of your choice, probably do the first one.
    }
    
    0 讨论(0)
提交回复
热议问题