按鈕與切換

Magnetic Button

磁吸按鈕:游標靠近時被吸向游標偏移,內層文字視差、離開後 spring 回彈。

把這個效果裝進你的專案

在專案資料夾執行指令,CLI 會加入原始碼與依賴套件,再依下方使用範例引用元件。

npx webberui@latest add magnetic-button

還沒有專案,或安裝遇到問題?看快速開始 →

Magnetic Button 是用 React、Tailwind CSS 與 Motion 做的磁吸按鈕(magnetic button/游標吸附按鈕)元件:滑鼠在按鈕上移動時,按鈕依游標相對中心的距離偏移,內層文字往反方向移動一半,離開後以 spring 彈回原位。

Playground

即時調整 props、程式碼片段同步更新——直接試出你要的樣子再複製。

0.35
編輯中的呼叫預設屬性
<MagneticButton/>

完整範例包含預覽的排版與資料。先安裝元件,再把範例檔貼入你的專案。

適用情境

  • 作品集或創意工作室網站的主要行動按鈕,例如「聯絡我們」「查看作品」。
  • Landing page hero 區塊裡唯一的 CTA,讓按鈕對游標有明顯回應。
  • 頁尾的聯絡區塊或電子報訂閱按鈕。
  • 不適合:表格列、工具列這類按鈕排得很密的地方,偏移後容易和相鄰按鈕視覺重疊。

安裝

npx webberui@latest add https://webberui.com/r/magnetic-button.json

安裝時會一併寫入 --wb-duration-fast CSS 變數到你的全域樣式。

使用

import { MagneticButton } from "@/components/ui/magnetic-button";

<MagneticButton onClick={() => console.log("clicked")}>
  開始使用
</MagneticButton>

範例

外框樣式

預設是實心按鈕,className 會和預設樣式合併,可以直接換成外框按鈕。

<MagneticButton className="border border-neutral-300 bg-transparent text-neutral-900 hover:bg-neutral-100 dark:border-neutral-700 dark:bg-transparent dark:text-neutral-100 dark:hover:bg-neutral-800">
  查看作品
</MagneticButton>

調整吸力與回彈手感

strength 越大偏移越明顯;springConfig 接受 Motion 的 spring 參數,降低 damping 會讓回彈多晃幾下。

<MagneticButton
  strength={0.5}
  springConfig={{ stiffness: 180, damping: 10, mass: 0.8 }}
  className="px-8 py-4 text-base"
>
  預約諮詢
</MagneticButton>

當成表單送出鈕

元件預設 type="button",傳入 type="submit" 會覆寫;其餘原生屬性如 disabled 也照常轉傳,停用時磁吸效果同步關閉。

<form action={subscribe} className="flex gap-2">
  <input name="email" type="email" required placeholder="you@example.com" className="rounded-full border px-4" />
  <MagneticButton type="submit" disabled={pending}>
    訂閱電子報
  </MagneticButton>
</form>

Props

Prop型別預設值說明
strengthnumber0.35磁吸強度:按鈕偏移量 = 游標相對中心距離 × strength,0 表示完全不動
springConfigSpringOptions{ stiffness: 260, damping: 18, mass: 0.7 }離開後回彈的 spring 參數
classNamestring—覆蓋預設樣式(預設為實心按鈕,可改為外框等變體)
childrenReactNode—按鈕內容

其餘 <button> 屬性(onClick、disabled、aria-* 等)皆直接透傳。

細節

  • 視差深度:按鈕朝游標偏移時,內層文字反向偏移一半,產生兩層深度感
  • spring 回彈:以 useMotionValue + useSpring 驅動,游標離開後帶慣性彈回原位
  • 觸控裝置自動停用:僅回應滑鼠的 pointer 事件(pointerType === "mouse"),觸控時就是一顆普通按鈕
  • 使用者系統開啟「減少動態效果」時停用磁吸,按鈕保持原位、功能不受影響
  • disabled 時同步停用磁吸

常見問題

可以在 Next.js App Router 使用嗎?

可以。檔案開頭已有 "use client",在 Server Component 頁面中照常 import 即可。

怎麼調整磁吸強度?

strength 決定偏移量:偏移距離等於游標相對按鈕中心的距離乘上 strength(預設 0.35),設為 0 就完全不動。回彈的手感用 springConfig 調整。

我自己也要監聽 onPointerMove,會被覆蓋嗎?

不會。元件會先呼叫你傳入的 onPointerMove 與 onPointerLeave,再執行磁吸邏輯。

手機或觸控裝置上會怎樣?

磁吸只回應滑鼠的 pointer 事件,觸控時就是一顆普通按鈕。系統開啟「減少動態效果」或按鈕 disabled 時,磁吸也會停用。

需要哪些依賴?

motion、clsx 與 tailwind-merge。不想用 CLI 時,可在安裝區的「手動」分頁複製原始碼。