如何在 < code >/< pre > 标记中逐字显示 < div > 标记?

我使用 <code>标签在 <pre>标签内显示代码在我的博客。不幸的是,它无法与 HTML 标记一起工作。有没有办法在 <pre><code>标签中显示“ <div>”而不实际将其解释为 HTML?这就是我现在所做的:

<pre>
<code>
.class {
color:red;
}
// I would like HTML code inside this
</code>
</pre>

除了 HTML 之外,其他都可以正常工作。有什么办法可以实现这个目标吗? 谢谢。

68397 次浏览

Unfortunately it doesn't work with HTML tags.

<code> means "This is code", <pre> means "White space in this markup is significant". Neither means "The content of this element should not be treated as HTML", so both work perfectly, even if they don't mean what you want them to mean.

Is there any way to show "<div>" inside of <pre> or <code> tag without actually interpreting it as HTML?

If you want to render a < character then use &lt;, with &gt; for > and &amp; for &.

You can't (in modern HTML) write markup and have it be interpreted as text.

Yes, with an escape xml function. You'll need to have jQuery enabled for it to work though.

<pre>
${fn:escapeXml('
<!-- all your code -->
')};
</pre>

Try CodeMirror (https://codemirror.net/)

It's a lightweight library that styles code in HTML. Here's a screenshot of what I'm referring to:

enter image description here

Worked well for us!

It seems like a readonly textarea does pretty much what you want.

<textarea readonly> <!-- html code --> </textarea>

You can use the "xmp" element. The <xmp></xmp> has been in HTML since the beginning and is supported by all browsers. Even it should not be used, it is broadly supported.

Everything inside <xmp></xmp> is taken as it is (no markup lke tags or character references is recognized there) except, for apparent reason, the end tag of the element itself.

Otherwise "xmp" is rendered like "pre".

Just escape the HTML tags. For example -

Replace < with &lt;

Replace > with &gt;

Complete lookup here

Try:

<xmp></xmp>

for exemple:

<pre>
<xmp><!-- your html code --></xmp>
</pre>

bye

Not the best answer, but you could try to put a comment inside the tag like this:

<pre>
<code<!-->>
...
<<!-->/<!-->code>
</pre>

This can be easily achieved with a little bit of javascript.

document.querySelectorAll("code").forEach(el => el.innerText = el.innerHTML);

Run snippet below to see it in action:

document.querySelectorAll("code").forEach(el => el.innerText = el.innerHTML);
pre {
padding: 1rem;
background-color: #eee;
border-radius: 0.25rem;
}
<pre>
<code>
.class {
color:red;
}
   

// I would like HTML code inside this
<h1>Hello this is a heading</h1>
</code>
</pre>

<pre>
<code><textarea>
<div>Now you can write Tags inside pre tag!</div>
</textarea><code>
<pre>

If you only need an opening tag, e.g <span>:

document.querySelectorAll('code').forEach(codeElement => {
codeElement.innerText = `<${codeElement.innerText}>`;
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals