Affix固钉

Affix 固钉

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

何时使用

当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。

页面可视范围过小时,慎用此功能以免遮挡页面内容。

代码演示

基本

最简单的用法。

<​template>  <​a-affix :offset-top="top">    <​a-button type="primary" @click="top += 10">Affix top<​/a-button>  <​/a-affix>  <​br />  <​a-affix :offset-bottom="bottom">    <​a-button type="primary" @click="bottom += 10">Affix bottom<​/a-button>  <​/a-affix><​/template><​script lang="ts">import { defineComponent, ref } from 'vue';export default defineComponent({  setup() {    const top = ref<​number>(10);    const bottom = ref<​number>(10);    return {      top,      bottom,    };  },});<​/script>

滚动容器

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

<​template>  <​div id="components-affix-demo-target" ref="containerRef" class="scrollable-container">    <​div class="background">      <​a-affix :target="() => containerRef">        <​a-button type="primary">Fixed at the top of container<​/a-button>      <​/a-affix>    <​/div>  <​/div><​/template><​script lang="ts">import { defineComponent, ref, VNode } from 'vue';export default defineComponent({  setup() {    const containerRef = ref<​VNode>();    return {      containerRef,    };  },});<​/script><​style>#components-affix-demo-target.scrollable-container {  height: 100px;  overflow-y: scroll;}#components-affix-demo-target .background {  padding-top: 60px;  height: 300px;  background-image: url('https://zos.alipayobjects.com/rmsportal/RmjwQiJorKyobvI.jpg');}<​/style>

固定状态改变的回调

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

<​template>  <​a-affix :offset-top="120" @change="change">    <​a-button>120px to affix top<​/a-button>  <​/a-affix><​/template><​script lang="ts">import { defineComponent } from 'vue';export default defineComponent({  setup() {    const change = (affixed: boolean) => {      console.log(affixed);    };    return {      change,    };  },});<​/script>

API

成员 说明 类型 默认值 版本
offsetBottom 距离窗口底部达到指定偏移量后触发 number
offsetTop 距离窗口顶部达到指定偏移量后触发 number
target 设置 Affix 需要监听其滚动事件的元素,值为一个返回对应 DOM 元素的函数 () => HTMLElement () => window

事件

事件名称 说明 回调参数 版本
change 固定状态改变时触发的回调函数 Function(affixed) 无

注意:Affix 内的元素不要使用绝对定位,如需要绝对定位的效果,可以直接设置 Affix 为绝对定位:

<​a-affix :style="{ position: 'absolute', top: y, left: x}">  ...<​/a-affix>

FAQ

Affix 使用 target 绑定容器时,元素会跑到容器外。

从性能角度考虑,我们只监听容器滚动事件。

相关 issue:#3938 #5642 #16120