如何在网页上显示HTML片段,而不需要将每个<替换为&lt;>和&gt;?

换句话说,是否有一个标记表示在点击结束标记之前不呈现HTML ?


当前回答

它可能并不适用于所有情况,但将代码片段放在文本区域内将它们显示为代码。

如果你不想让它看起来像一个实际的文本区域,你可以用CSS样式文本区域。

其他回答

我认为:

你想要编写100%有效的HTML5 你想把代码片段(几乎)文字放在HTML中 特别是<应该不需要转义

你所有的选项都在这棵树里:

with HTML syntax there are five kinds of elements those called "normal elements" (like <p>) can't have a literal < it would be considered the start of the next tag or comment void elements they have no content you could put your HTML in a data attribute (but this is true for all elements) that would need JavaScript to move the data elsewhere in double-quoted attributes, " and &thing; need escaping: &quot; and &amp;thing; respectively raw text elements <script> and <style> only they are never rendered visible but embedding your text in Javascript might be feasable Javascript allows for multi-line strings with backticks it could then be inserted dynamically a literal </script is not allowed anywhere in <script> escapable raw text elements <textarea> and <title> only <textarea> is a good candidate to wrap code in it is totally legal to write </html> in there not legal is the substring </textarea for obvious reasons escape this special case with &lt;/textarea or similar &thing; needs escaping: &amp;thing; foreign elements elements from MathML and SVG namespaces at least SVG allows embedding of HTML again... and CDATA is allowed there, so it seems to have potential with XML syntax covered by Konrad's answer

 

注意:>从来不需要转义。甚至在正常元素中也没有。

它可能并不适用于所有情况,但将代码片段放在文本区域内将它们显示为代码。

如果你不想让它看起来像一个实际的文本区域,你可以用CSS样式文本区域。

很简单.... 使用此xmp代码

    <xmp id="container">

&lt;xmp &gt;

    <p>a paragraph</p>

    &lt;/xmp &gt;

</xmp>

这是一种hack,但是我们可以使用类似的东西:

正文脚本{ 显示:块; 字体类型:等宽字体; 空白:前; } <脚本type = " text / html " > <标题> Hello World h1 > < / < ul > <li>享受这个狡猾的黑客, <李>或不! < / ul > > < /脚本

使用该CSS,浏览器将在主体中显示脚本。它不会尝试执行这个脚本,因为它有一个未知的类型text/html。在<script>中没有必要转义特殊字符,除非你想包含一个结束</script>标记。

我正在使用类似这样的东西在页面主体中显示可执行的JavaScript,这是一种“有文化的编程”。

在这个问题中还有更多的信息,标签什么时候应该可见,为什么可以?

这是一个简单的技巧,我已经在Safari和Firefox中尝试过了

<code>
    <span><</span>meta property="og:title" content="A very fine cuisine" /><br>
    <span><</span>meta property="og:image" content="http://www.example.com/image.png" />
</code>

它将显示如下:

你可以在这里现场观看