使用 JS 时字体真棒图标和面板无法正确显示

Font awesome icons and panels not showing properly when using JS

我正在尝试使用 JS 动态创建 HTML 元素。但是,这样做时面板和字体真棒图标无法正确显示。

这是我想用JS动态创建的HTML代码。

<div class="row" id="row">
    <div class="col">
        <div class="panel-custom border colorized">
            <div class="fa fa-chevron-right right-arrow"></div>
        </div>
    </div>
</div>

我的JS代码:

  let row = document.getElementById('row');
  let col = document.createElement('col');
  let panelCustom = document.createElement('panel-custom');
  let fa = document.createElement('fa');

  panelCustom.classList.add("colorized");
  panelCustom.classList.add("border");
  fa.classList.add("fa-chevron-right");
  fa.classList.add("right-arrow");

  row.appendChild(col);
  col.appendChild(panelCustom);
  panelCustom.appendChild(fa);

您实际上无法创建 "col"、"panel-custom" 或 "fa" 类型的元素,就像您在此处尝试的那样:

let col = document.createElement('col');
let panelCustom = document.createElement('panel-custom');
let fa = document.createElement('fa');

这些是无效的 HTML 元素。事实上,它们应该是 <div> 元素,就像您的 HTML 样本中那样。改为创建 <div> 个元素:

let col = document.createElement('div');
let panelCustom = document.createElement('div');
let fa = document.createElement('div');

然后添加需要的类:

panelCustom.classList.add("panel-custom");
panelCustom.classList.add("colorized");
panelCustom.classList.add("border");
// etc.

您可以试试这个(它应该会按预期工作):

let row = document.createElement('div');
row.className = "row";

let col = document.createElement('div');
col.className = "col";

let panelCustom = document.createElement('div');
panelCustom.className = "panel-custom colorized border";

let fa = document.createElement('i');
fa.className = "fa fa-chevron-right right-arrow";

panelCustom.appendChild(fa);
col.appendChild(panelCustom);
row.appendChild(col);
document.body.appendChild(row);
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" rel="stylesheet"/>