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

自定义JS光标:Hover加载data-img图片并优化空标签问题

自定义JavaScript光标优化实现

核心思路

去掉预先生成的空img标签,仅在hover带有data-img属性的元素时,动态创建img节点并设置图片路径;离开元素时销毁该img节点,保持光标容器在非激活状态下的简洁性。

代码实现

HTML结构

只保留基础光标容器,无需提前嵌入空img:

<div class="custom-cursor"></div>

<!-- 示例可触发图片光标的元素 -->
<div class="demo-card" data-img="./assets/product-1.jpg">查看产品1</div>
<div class="demo-card" data-img="./assets/product-2.jpg">查看产品2</div>

CSS样式

定义基础光标及图片光标样式:

.custom-cursor {
  position: fixed;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.15);
  pointer-events: none;
  z-index: 9999;
  transform: translate(-50%, -50%);
  transition: all 0.12s ease;
}

/* 激活状态下的光标样式 */
.custom-cursor.active {
  background: transparent;
  border: 1px solid rgba(0, 0, 0, 0.2);
}

.custom-cursor img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

JavaScript逻辑

实现光标跟随、动态创建/销毁图片节点的核心功能:

const cursor = document.querySelector('.custom-cursor');
let activeImg = null;

// 实时更新光标位置
document.addEventListener('mousemove', (e) => {
  cursor.style.left = `${e.clientX}px`;
  cursor.style.top = `${e.clientY}px`;
});

// 绑定所有带data-img元素的hover事件
document.querySelectorAll('[data-img]').forEach(target => {
  target.addEventListener('mouseenter', () => {
    // 创建img元素并赋值路径
    activeImg = document.createElement('img');
    activeImg.src = target.getAttribute('data-img');
    cursor.appendChild(activeImg);
    cursor.classList.add('active');
  });

  target.addEventListener('mouseleave', () => {
    // 移除图片节点并清空引用
    if (activeImg) {
      cursor.removeChild(activeImg);
      activeImg = null;
    }
    cursor.classList.remove('active');
  });
});

可选优化点

  • 图片预加载:对高频触发的图片,可提前通过new Image()预加载,避免hover时的加载延迟;
  • 错误处理:给img添加error事件,加载失败时显示默认占位样式;
  • 样式扩展:根据data-img的不同属性值,动态调整光标尺寸、形状等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:32:15