Appearance
Affix 固钉
将页面元素钉在可视范围。
代码演示
基础用法
最简单的用法。
vue
<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 setup>
import { ref } from 'vue'
const top = ref(10)
const bottom = ref(10)
</script>固定状态改变的回调
可以获得是否固定的状态。
vue
<template>
<a-affix :offset-top="120" @change="change">
<a-button>120px to affix top</a-button>
</a-affix>
</template>
<script setup>
const change = (affixed) => {
console.log(affixed)
}
</script>滚动容器
用 target 设置 Affix 需要监听其滚动事件的元素,默认为 window。
vue
<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 setup>
import { ref } from 'vue'
const containerRef = ref()
</script>
<style scoped>
#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>API
| 成员 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| offsetBottom | 距离窗口底部达到指定偏移量后触发 | number | |
| offsetTop | 距离窗口顶部达到指定偏移量后触发 | number | 0 |
| target | 设置 Affix 需要监听其滚动事件的元素,值为一个返回对应 DOM 元素的函数 () => HTMLElement | () => window |
事件
| 事件名称 | 说明 | 回调参数 |
|---|---|---|
| change | 固定状态改变时触发的回调函数 | (affixed?: boolean) => void |
TIP
Affix 内的元素不要使用绝对定位,如需要绝对定位的效果,可以直接设置 Affix 为绝对定位:
html
<a-affix :style="{ position: 'absolute', top: y, left: x}">...</a-affix>
