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

能否实现自定义光标悬停时仅光标区域内文本属性变更?

自定义光标悬停文本的局部样式实现方案

需求回顾

  • 自定义光标,悬停时光标区域内的黑色文本变为白色
  • 红色文本在光标区域仅显示黄色描边
  • 仅光标覆盖区域的文本样式变化

实现代码

HTML

<div class="text-container">
  <span class="black-text">黑色文本示例</span>
  <span class="red-text" data-text="红色文本示例">红色文本示例</span>
</div>
<div class="custom-cursor"></div>

CSS

body {
  margin: 0;
  padding: 3rem;
  background: #ffffff;
  font-size: 2.5rem;
}

.text-container {
  position: relative;
}

.black-text {
  color: #000000;
}

.red-text {
  position: relative;
  color: #ff3333;
}

/* 红色文本的黄色描边层 */
.red-text::after {
  content: attr(data-text);
  position: absolute;
  top: 0;
  left: 0;
  -webkit-text-stroke: 2px #ffff00;
  color: transparent;
  mix-blend-mode: screen;
  opacity: 0;
  transition: opacity 0.1s;
}

/* 自定义光标 */
.custom-cursor {
  position: fixed;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: #ffffff;
  pointer-events: none;
  mix-blend-mode: difference;
  z-index: 100;
}

/* 光标悬停文本区域时,显示红色文本的描边层 */
.custom-cursor.active ~ .text-container .red-text::after {
  opacity: 1;
  clip-path: circle(40px at var(--mouse-x) var(--mouse-y));
}

JavaScript

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

document.addEventListener('mousemove', (e) => {
  // 控制光标位置
  cursor.style.left = `${e.clientX - 40}px`;
  cursor.style.top = `${e.clientY - 40}px`;
  
  // 设置鼠标坐标变量,用于clip-path定位
  document.documentElement.style.setProperty('--mouse-x', `${e.clientX}px`);
  document.documentElement.style.setProperty('--mouse-y', `${e.clientY}px`);
  
  // 判断是否悬停在文本容器上
  const isOverText = e.target.closest('.text-container') !== null;
  cursor.classList.toggle('active', isOverText);
});

方案说明

  1. 黑色文本变白:利用mix-blend-mode: difference,白色光标与黑色文本混合后会反转成白色,完美实现局部变色效果。
  2. 红色文本黄色描边:通过伪元素生成仅含黄色描边的文本层,默认隐藏;当光标悬停文本区域时,用clip-path将描边层的显示范围限制在光标圆形区域内,结合mix-blend-mode: screen让描边与原红色文本混合,只保留黄色描边效果。
  3. 光标跟随:通过JS监听鼠标移动事件,实时更新自定义光标位置和鼠标坐标变量,确保样式变化精准对应光标区域。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:32:38