如何使用 w3codecolor 进行 html 语法高亮显示?

问题描述

基于示例 here 我正在尝试使用 w3codecolor 进行 html 语法突出显示。 我添加了对 https://www.w3schools.com/w3css/4/w3.csshttps://www.w3schools.com/lib/w3codecolor.js 的引用,然后调用 w3CodeColor(); 函数

然而,它实际上不是显示 html,而是呈现 html 输出

请注意,我的 html 具有我想按原样呈现的自定义元素。

DEMO

HTML

<div class="w3-panel w3-card w3-light-grey">
<h4>Example</h4>
<div class="w3-code htmlHigh notranslate">
    <file label="Please select a file." name="myimage" storage="{{bucket}}" validation="filetypes:.pdf|.txt|.xlsx maxfilesize:12345"></file>
    
    <dropdown label="Can you select a single state?" name="state">
        <option label="" value=""></option>
        <option label="Oklahoma" value="OK"></option>
        <option label="Texas" value="TX"></option>
        <option label="New York" value="NY"></option>
    </dropdown>
    
    <input id="firstname" name="firstname" />
</div>

更新 1
根据建议,我使用 jQuery 转义了 html,它似乎正在工作。但是它不保留制表符缩进。关于如何保持标签缩进的任何建议?

//转义

 $(".w3-code").each(function (i,v) {       
        var $code = $(v);
        $code.text($code.html());
        w3CodeColor();
 });

DEMO

解决方法

这是一个语法高亮。

只是一个语法高亮。

不会深入您的 HTML 源代码并将您嵌入的 XML 转换为您的 XML 的 HTML 表示。

如果您希望显示 & 字符,则需要对其进行转义 (&amp;)。 HTML 中的其他特殊字符也是如此。

一旦您编写了 HTML 以显示您想要的文本,语法高亮器就可以对其进行操作。

,

因为你可以在 w3 的 seeonline demo(找到 here):

<div class="w3-panel w3-card w3-light-grey"> 
  <h4>HTML Example</h4>
  <div class="w3-code htmlHigh notranslate">
    &lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>
    &lt;title&gt;HTML Tutorial&lt;/title&gt;<br>
    &lt;body&gt;<br><br>
    &lt;h1&gt;This is a heading&lt;/h1&gt;<br>
    &lt;p&gt;This is a paragraph.&lt;/p&gt;<br><br>
    &lt;/body&gt;<br>
    &lt;/html&gt;
  </div>
</div>

您需要转义这些特殊字符,@Quentin 解释得很好。

,

添加 pre 标签有帮助

DEMO

 <div class="w3-panel w3-card w3-light-grey">
    <h4>Example</h4>
    <pre>
      <div class="w3-code htmlHigh notranslate">
          <file label="Please select a file." name="myimage" storage="{{bucket}}" validation="filetypes:.pdf|.txt|.xlsx maxfilesize:12345"></file>
          <dropdown label="Can you select a single state?" name="state">
              <option label="" value=""></option>
              <option label="Oklahoma" value="OK"></option>
              <option label="Texas" value="TX"></option>
              <option label="New York" value="NY"></option>
          </dropdown>

          <input id="firstname" name="firstname" />
      </div>
    </pre>
</div>

JS

 $(".w3-code").each(function (i,v) {       
        var $code = $(v);
        $code.text($code.html());
        w3CodeColor();
    });