Affix 固钉

将页面元素钉在可视范围内

何时使用

  • 需要让页面元素在滚动时固定在可视范围内时。
  • 需要固定到顶部或底部指定偏移量时。
  • 需要监听固定状态变化时。

导入

import { Affix } from "@reglow/reui";

基础用法

最简单的用法,距离窗口顶部达到指定偏移量后触发固定。

<script setup lang="ts">
import { ref } from "vue";
import { Affix } from "@reglow/reui";
import { Button } from "@reglow/reui";

const top = ref(100);
</script>

<template>
  <Affix :offset-top="top">
    <Button variant="default" @click="top += 10">
      Affix top: {{ top }}
    </Button>
  </Affix>
</template>

更多示例

固定在底部

距离窗口底部达到指定偏移量后触发固定。

<template>
  <Affix :offset-bottom="100">
    <Button type="primary">Affix bottom: 100px</Button>
  </Affix>
</template>

固定状态改变的回调

可以获得是否固定的状态。

<script setup lang="ts">
import { Affix } from "@reglow/reui";
import { Button } from "@reglow/reui";

function onChange(affixed: boolean) {
  console.log("affixed:", affixed);
}
</script>

<template>
  <Affix :offset-top="120" @change="onChange">
    <Button>120px to affix top</Button>
  </Affix>
</template>

滚动容器

target 设置 Affix 需要监听其滚动事件的元素,默认为 window

<script setup lang="ts">
import { ref } from "vue";
import { Affix } from "@reglow/reui";
import { Button } from "@reglow/reui";

const containerRef = ref<HTMLElement | null>(null);
</script>

<template>
  <div
    ref="containerRef"
    class="h-[400px] overflow-auto border border-primary"
  >
    <div class="h-[1000px] p-4">
      <Affix :target="() => containerRef.value">
        <Button variant="default">Fixed at the top of container</Button>
      </Affix>
    </div>
  </div>
</template>

API

Affix Props

参数说明类型默认值
offsetTop距离窗口顶部达到指定偏移量后触发number0
offsetBottom距离窗口底部达到指定偏移量后触发number-
target设置 Affix 需要监听其滚动事件的元素() => Window | HTMLElement | null() => window
class自定义类名string-
style自定义样式CSSProperties-

Affix Events

事件说明回调参数
change固定状态改变时触发的回调(affixed: boolean) => void

Affix Slots

插槽说明
default需要固定的内容

注意事项

  • Affix 内的元素不要使用绝对定位,如需要绝对定位的效果,可以直接设置 Affix 为绝对定位。
  • 一般只适用于单向滚动的区域,只支持在垂直滚动容器中使用。
  • 组件在固钉时会自动生成占位元素,保持原有文档流位置不塌陷。