跳至主要内容

useSticky

跟蹤元素是否粘滞

Usage

即時編輯器
function Demo() {
  const element = useRef<HTMLDivElement>(null);
  const [isSticky] = useSticky(element, {
    // header fixed height
    nav: 64,
  });

  const stickyStyle: CSSProperties = isSticky
    ? {
        position: "fixed",
        top: 64,
        zIndex: 50,
        height: 20,
      }
    : {
        height: 20,
      };

  const guardStyle: CSSProperties = {
    width: 1,
    height: 1,
  };

  return (
    <div style={{height: 300,overflow: 'scroll'}}>
      <div ref={element} style={guardStyle} />
      <button style={stickyStyle}>
        {isSticky ? "stickying" : "not sticky"}
      </button>
      <div style={{ height: "100vh" }} />
    </div>
  );
};
結果

API

useSticky

Returns

[boolean, React.Dispatch<React.SetStateAction<boolean>>]: 包含以下元素的元組:

  • 當前是否粘滞。
  • 更新粘滞值的函數。

Arguments

參數名描述類型預設值
targetElementdom元素BasicTarget<HTMLElement> (必填)-
params可选参数UseStickyParams (必填)-
scrollElement滚动容器BasicTarget<HTMLElement>-

UseStickyParams

參數名描述類型預設值
axis滚动方向'x' | 'y'y
nav沉浸式高度/宽度number (必填)0

BasicTarget

export type BasicTarget<T extends TargetType = Element> = (() => TargetValue<T>) | TargetValue<T> | MutableRefObject<TargetValue<T>>;

TargetValue

type TargetValue<T> = T | undefined | null;

TargetType

type TargetType = HTMLElement | Element | Window | Document | EventTarget;
Squarespace
Squarespace makes your marketing, customer management, and checkout flow effortless—all on a single platform.
Get Started