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

鼠标悬停li时追加Font Awesome图标及定位的JS问题排查

问题解决:Li元素悬停追加Font Awesome图标并定位到右侧

问题概述

已在HTML中引入Font Awesome,需要实现:鼠标悬停在<li>元素上时,在该行最右侧追加一个图标;同时需解决图标定位到<li>最右侧的样式问题,当前代码无法正常运行。

原代码错误分析

  1. 元素创建错误:document.createElement('icon')是无效标签,应创建Font Awesome所需的<i>元素
  2. 类名操作错误:classlist拼写错误(应为classList),且直接赋值HTML字符串的方式错误,需用classList.add()添加类名
  3. 未遍历元素:querySelectorAll返回的是NodeList集合,需遍历每个<li>绑定事件
  4. 移除元素风险:鼠标移出时未判断图标是否存在,可能触发移除不存在元素的报错

修正后的完整代码

JavaScript代码

const liElements = document.querySelectorAll("li");

liElements.forEach(li => {
  // 创建Font Awesome图标元素
  const icon = document.createElement('i');
  // 添加Font Awesome样式类和自定义类
  icon.classList.add('fa-thin', 'fa-house', 'hover-icon');

  li.addEventListener('mouseenter', () => {
    li.appendChild(icon);
  });

  li.addEventListener('mouseleave', () => {
    // 确保图标存在时再移除
    if (icon.parentElement === li) {
      li.removeChild(icon);
    }
  });
});

CSS代码(新增图标定位样式)

ul {
  margin: 0;
  padding: 0;
}

ul li {
  cursor: pointer;
  position: relative;
  padding: 12px 8px 12px 40px;
  background: #eee;
  font-size: 18px;
  transition: 0.2s;
  list-style-type: none;

  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

ul li:nth-child(odd) {
  background: #f9f9f9;
}

ul li:hover {
  background: #ddd;
}

ul li.checked {
  background: #276678;
  color: #fff;
  text-decoration: line-through;
}

ul li.checked::before {
  content: "";
  position: absolute;
  border-color: #fff;
  border-style: solid;
  border-width: 0 2px 2px 0;
  top: 10px;
  left: 16px;
  transform: rotate(45deg);
  height: 15px;
  width: 7px;
}

/* 新增:悬停图标的定位样式 */
.hover-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
}

HTML代码(无需修改)

<ul id="DadsList">
  <li>3 liters of Milk</li>
  <li>Bread</li>
</ul>

关键说明

  • 利用<li>的position: relative作为定位参考,将图标设置为position: absolute,通过right属性固定到右侧,transform: translateY(-50%)实现垂直居中
  • 遍历所有<li>元素并分别绑定事件,确保每个列表项都能触发悬停效果
  • 移除图标前先判断父元素,避免DOM操作报错

内容的提问来源于stack exchange,提问作者Özcan Sert

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:57:49