code inside pre goes in one line on IE8

痞子三分冷 提交于 2019-12-06 00:47:44
Doug

"IE applies HTML normalization to the data that is assigned to the innerHTML property. This causes incorrect display of whitespace in elements that ought to preserve formatting, such as <pre> and <textarea>."

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

The \n solution is probably going to be your best shot (the only other option is to use innerText it seems, but I prefer your solution).

atm my solution is to add this line at the end:

.replace(/\n/g, '<br\>')

in my htmlEscape, so it's like this:

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')         
            .replace(/</g, '&lt;')                      
            .replace(/>/g, '&gt;')
        .replace(/\n/g, '<br\>');
}

please post your answer if you know a better one

If the problem is IE using innerHTML, then don't use innerHTML:

document.getElementById("tt").appendChild(document.createTextNode(x));

instead of

$('#tt').html(htmlEscape(x));   
Thomas

Use

document.getElementById("ID").textContent = 'YOUR TEXT';

The default behaviour of the <pre> element is to display all white space, including line feeds, so by default you should be seeing new lines where you have \n characters.

If you're not seeing that, then it implies that the default behaviour of the element has been overridden by your stylesheets.

This is done using the CSS white-space property. By default the <pre> tag has this property set to white-space:pre;. Setting the white-space property like this will cause the <pre> element - or indeed any other element - to display all white space, including line feeds, as per the default for the <pre> element.

There are a number of possible settings for the white-space property. You can find examples of them all and how they affect the layout here: http://www.impressivewebs.com/css-white-space/

So if you want the <pre> to act as normal, you should either remove the styles which are currently setting the white-space property, or override them and set it back to the default value.

Hope that helps.

ps - if you plan to try out the various values for white-space as listed on the page I linked above, please note that older versions of IE (IE7 and earlier) may not support all possible options for this property. If you're worried about this, then QuirksMode.org has a compatibility table which may help you.

Use

                 replace('\r','&lt;br/&gt;')                               .
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!