反色混合光标

圆形光标会反转经过的内容颜色,移到链接上时放大成一面透镜。

  • JS
  • 光标
  • 跟随指针
  • 收录于

靠近一点看

查看案例 →

AI 提示词

用 React 制作一个会反转下方内容颜色的自定义光标。在区域内隐藏原生光标(cursor: none,仅在 (pointer: fine) 时生效),并渲染一个 20px 的白色圆形,设置 position: absolute、pointer-events: none 和 mix-blend-mode: difference,让它反转下方的文字和背景。pointermove 时直接把 transform 设为 translate(x, y) translate(-50%, -50%)(无延迟)。当指针位于带 data-cursor="grow" 的元素上时,在 250ms 内用 cubic-bezier(0.16, 1, 0.3, 1) 把圆形放大到 4 倍。pointerleave 时隐藏。保留可见的键盘焦点样式,因为自定义光标对键盘用户没有作用。在 prefers-reduced-motion 下保留反色效果,但跳过缩放过渡。内容为标题“靠近一点看”和链接“查看案例”。

源代码

Demo.tsx
'use client'

import { useRef } from 'react'
import s from './demo.module.css'

export default function BlendCursor({ labels }: { labels: Record<string, string> }) {
  const dot = useRef<HTMLSpanElement>(null)

  const onMove = (e: React.PointerEvent<HTMLDivElement>) => {
    if (e.pointerType === 'touch' || !dot.current) return
    const r = e.currentTarget.getBoundingClientRect()
    const grow = (e.target as HTMLElement).closest('[data-cursor="grow"]') !== null
    dot.current.style.transform = `translate(${e.clientX - r.left}px, ${e.clientY - r.top}px) translate(-50%, -50%)`
    dot.current.dataset.grow = String(grow)
    dot.current.dataset.on = 'true'
  }

  return (
    <div className={s.area} onPointerMove={onMove} onPointerLeave={() => dot.current && (dot.current.dataset.on = 'false')}>
      <p className={s.text}>{labels.text}</p>
      <a className={s.link} href="#" data-cursor="grow" onClick={(e) => e.preventDefault()}>
        {labels.link} →
      </a>
      <span ref={dot} className={s.cursor} aria-hidden="true">
        <span className={s.lens} />
      </span>
    </div>
  )
}
demo.module.css
.area {
  --lens: oklch(100% 0 0);
  position: absolute;
  inset: 0;
  display: grid;
  place-content: center;
  justify-items: center;
  gap: 14px;
  overflow: hidden;
}

@media (pointer: fine) {
  .area, .area * { cursor: none; }
}

.text {
  margin: 0;
  font: 700 2.4rem / 1 var(--font-display);
  letter-spacing: -0.03em;
  color: var(--stage-ink);
  white-space: nowrap;
}

.link {
  padding: 10px 16px;
  border-radius: 999px;
  background: var(--stage-accent);
  color: var(--stage-accent-ink);
  font: 600 var(--text-sm) / 1 var(--font-body);
  text-decoration: none;
  white-space: nowrap;
}

.link:focus-visible { outline: 2px solid var(--color-focus); outline-offset: 3px; }

.cursor {
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none;
  mix-blend-mode: difference;
  opacity: 0;
}

.cursor[data-on='true'] { opacity: 1; }

.lens {
  display: block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: var(--lens);
  transition: transform 250ms var(--ease-out);
}

.cursor[data-grow='true'] .lens { transform: scale(4); }

@media (prefers-reduced-motion: reduce) {
  .lens { transition: none; }
}

投稿创意

看到想收录的动效或主题?简单描述一下,会打开一个预先填好的 GitHub Issue,确认后即可提交。

你想投稿的是?

需要 GitHub 账号,投稿内容会公开。