< pre>标记在IE中设置innerHTML时丢失换行符 [英] <pre> tag loses line breaks when setting innerHTML in IE

查看:62
本文介绍了< pre>标记在IE中设置innerHTML时丢失换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Prototype的PeriodicalUpdater用ajax调用的结果更新div.据我了解,通过设置其innerHTML来更新div.

I'm using Prototype's PeriodicalUpdater to update a div with the results of an ajax call. As I understand it, the div is updated by setting its innerHTML.

div包裹在< pre> 标记中.在Firefox中,< pre> 格式可以按预期工作,但在IE中,文本全部以一行结尾.

The div is wrapped in a <pre> tag. In Firefox, the <pre> formatting works as expected, but in IE, the text all ends up on one line.

此处找到了一些示例代码,它说明了问题.在Firefox中, abc def 位于不同的行;在IE中是同一行.

Here's some sample code found here which illustrates the problem. In Firefox, abc is on different line than def; in IE it's on the same line.

    <html>
    <head>
      <title>IE preformatted text sucks</title>
    </head>
    <body>
      <pre id="test">
        a b c
        d e f
      </pre>
      <script type="text/javascript"><!--
      var textContent = document.getElementById("test").innerText;
      textContent = textContent.replace("a", "<span style=\"color:red;\">a</span>");
      document.getElementById("test").style.whiteSpace = "pre";
      document.getElementById("test").innerHTML = textContent;
      --></script>
    </body>
    </html>

有人知道解决这个问题的方法吗?

Anyone know of a way to get around this problem?

推荐答案

设置innerHTML会启动HTML解析器,该解析器会忽略多余的空格(包括硬返回).如果您更改方法以包括< pre>标记在字符串中,因此效果很好,因为HTML解析器保留了硬返回值.

Setting innerHTML fires up an HTML parser, which ignores excess whitespace including hard returns. If you change your method to include the <pre> tag in the string, it works fine because the HTML parser retains the hard returns.

运行示例页面后,您可以通过执行查看生成的源"来查看此操作:

You can see this in action by doing a View Generated Source after you run your sample page:

<PRE id="test" style="WHITE-SPACE: pre"><SPAN style="COLOR: red">a</SPAN> b c d e f </PRE>

您可以在此处看到,强硬的回报"不再是< pre>内容的一部分.标签.

You can see here that the hard return is no longer part of the content of the <pre> tag.

这篇关于&lt; pre&gt;标记在IE中设置innerHTML时丢失换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆