You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态创建的Font Awesome图标已存在但无法显示问题求助

解决拖拽成功后Font Awesome图标不显示的问题

嘿,我仔细看了你的代码,发现图标没法正常显示主要是几个小细节没处理对,咱们一步步来修复:

1. 先搞定最关键的语法错误

你在drop函数里给container2设置innerHTML的时候,class属性没加引号,这会让浏览器把fa-solid当成单独的属性,而不是图标的类名,自然识别不了Font Awesome的样式:

原来的错误代码:

container2.innerHTML = "<i class=fa-solid fa-circle-check icon></i>"

改成这样(给class加双引号):

container2.innerHTML = '<i class="fa-solid fa-circle-check icon"></i>';

2. 调整Font Awesome图标的CSS写法

Font Awesome是字体图标,不能用width/height来控制大小,得用font-size。另外你写的display: visible是无效属性,正确的应该用display: block或者inline-block,我给你调整了CSS:

.fa-solid {
  font-size: 30px; /* 用字体大小控制图标尺寸 */
  display: block;
  color: green; /* 绿色更符合成功提示的视觉 */
  margin: 20px auto; /* 让图标在容器里居中 */
}

3. 可选优化:不要覆盖原有内容

如果你不想把container2里的<p>和<div>都替换掉,可以用appendChild来添加图标,而不是直接覆盖innerHTML,这样原来的内容会保留:

const checkIcon = document.createElement('i');
checkIcon.classList.add('fa-solid', 'fa-circle-check', 'icon');
container2.appendChild(checkIcon);

4. 最后检查一下潜在问题

  • 你引入的Font Awesome CDN链接是有效的(v6.0.0没问题),如果后续有版本更新可以留意;
  • 你已经用console.log(container2)确认元素存在,这部分没问题;

修复后的drop函数示例

function drop(e) {
  let imgSrc = currentDrag.src;
  let x = this.id;
  let newRegex = new RegExp(x, "g");
  let searchResult = newRegex.test(imgSrc);
  if(!searchResult) return e.preventDefault();
  
  currentDrag.parentElement.style.display = "none";
  this.append(currentDrag);
  setTimeout(() => this.style.display = "none", 2000);
  
  // 用appendChild的方式添加图标(推荐)
  const checkIcon = document.createElement('i');
  checkIcon.classList.add('fa-solid', 'fa-circle-check', 'icon');
  container2.appendChild(checkIcon);
}

这样调整之后,拖拽成功后应该就能看到正常显示的对勾图标啦!如果还是有问题,打开浏览器控制台看看有没有报错信息,能更快定位问题~

内容的提问来源于stack exchange,提问作者alwaysLearning

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 14:42:38