如何在网页上显示HTML片段,而不需要将每个<替换为<>和>?
换句话说,是否有一个标记表示在点击结束标记之前不呈现HTML ?
如何在网页上显示HTML片段,而不需要将每个<替换为<>和>?
换句话说,是否有一个标记表示在点击结束标记之前不呈现HTML ?
当前回答
示例1:
<pre>
This text has
been formatted using
the HTML pre tag. The brower should
display all white space
as it was entered.
</pre>
示例2:
<pre>
<code>
My pre-formatted code
here.
</code>
</pre>
示例3: (如果你实际上是在“引用”一段代码,那么标记应该是)
<blockquote>
<pre>
<code>
My pre-formatted "quoted" code here.
</code>
</pre>
</blockquote>
其他回答
在HTML中有几种方法可以转义所有内容,但都不是很好。
或者你可以放入一个iframe来加载一个普通的旧文本文件。
已废弃的<xmp>标记实际上就是这样做的,但它不再是XHTML规范的一部分。尽管它在当前所有浏览器中仍然有效。
这里有另一个想法,一个hack/parlor trick,你可以把代码放在一个文本区域,像这样:
<textarea disabled="true" style="border: none;background-color:white;">
<p>test</p>
</textarea>
将尖括号和这样的代码放在文本区域内是无效的HTML,在不同的浏览器中会导致未定义的行为。在Internet Explorer中,HTML是解释的,而Mozilla、Chrome和Safari则不解释。
如果你想要它是不可编辑的,看起来不同,那么你可以很容易地使用CSS样式。唯一的问题是浏览器会在右下角添加一个小的拖动句柄来调整方框的大小。或者,尝试使用input标记。
正确的方式注入代码到你的文本区域是使用服务器端语言,比如PHP:
<textarea disabled="true" style="border: none;background-color:white;">
<?php echo '<p>test</p>'; ?>
</textarea>
然后,它绕过html解释器,并在所有浏览器中一致地将未解释的文本放入文本区域。
除此之外,如果使用静态HTML,唯一的方法是自己转义代码,如果使用这种技术,则使用服务器端方法,如。net的HtmlEncode()。
如果您正在寻找与框架一起工作的解决方案。
const code = `
<div>
this will work in react
<div>
`
<pre>
<code>{code}</code>
</pre>
你可以用css给它一个漂亮的外观:
pre code {
background-color: #eee;
border: 1px solid #999;
display: block;
padding: 20px;
}
下面是几个答案的组合:
函数c(s) { 返回s.split(“& lt;”). join(“<”).split(“在”). join(“>”).split (", ") . join(“&”) } displayMe。innerHTML = ok.innerHTML; console.log ( c (ok.innerHTML) ) <textarea style="display:none" id="ok"> <脚本> console.log(“hello”,5和9); > < /脚本 textarea > < / < div id = " displayMe " > < / div >
我认为:
你想要编写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: " and &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 </textarea or similar &thing; needs escaping: &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
注意:>从来不需要转义。甚至在正常元素中也没有。