Affix固钉 - 图1

Affix 固钉

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

何时使用

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

代码演示

Affix固钉 - 图2

基本

最简单的用法。

  1. <template>
  2. <div>
  3. <a-affix :offset-top="top">
  4. <a-button type="primary" @click="top += 10">
  5. Affix top
  6. </a-button>
  7. </a-affix>
  8. <br />
  9. <a-affix :offset-bottom="bottom">
  10. <a-button type="primary" @click="bottom += 10">
  11. Affix bottom
  12. </a-button>
  13. </a-affix>
  14. </div>
  15. </template>
  16. <script>
  17. export default {
  18. data() {
  19. return {
  20. top: 10,
  21. bottom: 10,
  22. };
  23. },
  24. };
  25. </script>

Affix固钉 - 图3

滚动容器

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

  1. <template>
  2. <div id="components-affix-demo-target" ref="container" class="scrollable-container">
  3. <div class="background">
  4. <a-affix :target="() => this.$refs.container">
  5. <a-button type="primary">
  6. Fixed at the top of container
  7. </a-button>
  8. </a-affix>
  9. </div>
  10. </div>
  11. </template>
  12. <style>
  13. #components-affix-demo-target.scrollable-container {
  14. height: 100px;
  15. overflow-y: scroll;
  16. }
  17. #components-affix-demo-target .background {
  18. padding-top: 60px;
  19. height: 300px;
  20. background-image: url('https://zos.alipayobjects.com/rmsportal/RmjwQiJorKyobvI.jpg');
  21. }
  22. </style>

Affix固钉 - 图4

固定状态改变的回调

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

  1. <template>
  2. <a-affix :offset-top="120" @change="change">
  3. <a-button>120px to affix top</a-button>
  4. </a-affix>
  5. </template>
  6. <script>
  7. export default {
  8. methods: {
  9. change(affixed) {
  10. console.log(affixed);
  11. },
  12. },
  13. };
  14. </script>

API

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

事件

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

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

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

FAQ

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

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

相关 issue:#3938 #5642 #16120