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

如何让自定义光标在Astro+Preact页面间保持状态?

Astro + Preact 中 ipad-cursor 页面切换后失效的修复方案

问题场景

在 Astro + Preact 搭建的作品集中使用 ipad-cursor 库实现自定义光标,已添加 transition:name 和 transition:persist 尝试持久化光标状态,但页面切换时光标会变回 Windows 系统默认样式,需刷新页面才能恢复。

修复方案

核心问题在于 Astro 的页面切换(Partial Hydration)过程中,系统光标样式可能被重置,且库的事件监听或内部状态可能失效。以下是具体修复步骤:

1. 修改 CustomCursor 组件,监听 Astro 页面切换事件

调整组件的 useEffect,添加对 Astro 页面切换完成事件的监听,确保每次页面切换后重新刷新光标状态:

import { useEffect } from "preact/hooks";
import { initCursor, updateCursor } from "ipad-cursor";

const CustomCursor = () => {
  useEffect(() => {
    const setupCursor = () => {
      // 强制隐藏系统光标,避免页面切换时被重置
      document.body.style.cursor = "none";

      if (!window.cursorInitialized) {
        initCursor({
          normalStyle: { background: "rgba(0, 0, 0, 0.5)" },
          textStyle: { background: "blue" },
          blockStyle: { background: "green" },
        });
        window.cursorInitialized = true;
      } else {
        // 已初始化则刷新光标状态,确保事件监听正常
        updateCursor();
      }
    };

    // 初始加载时配置光标
    setupCursor();

    // 监听 Astro 页面切换完成事件
    const handlePageSwap = () => setupCursor();
    window.addEventListener("astro:after-swap", handlePageSwap);

    // 组件卸载时移除监听
    return () => window.removeEventListener("astro:after-swap", handlePageSwap);
  }, []);

  return null;
};

export default CustomCursor;

2. 确保组件持久化配置正确

保持布局中的组件引入,可额外添加固定 key 强化持久化效果:

<Cursor client:load transition:name="cursor" transition:persist key="custom-cursor"/>

3. 额外排查点

  • 检查页面切换后 body 的 cursor 样式是否被重置:在浏览器开发者工具中查看 body 元素的 cursor 属性,若为默认值,说明需要强制设置为 none。
  • 若上述方案仍无效,可尝试在页面切换时重新初始化光标(取消注释组件内的销毁/重初始化代码),确保库的内部状态完全重置。

内容的提问来源于stack exchange,提问作者Fabián Casas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:46:14