Affix 固钉

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

何时使用

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

代码演示

Affix固钉 - 图1

基本

最简单的用法。

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

Affix固钉 - 图2

固定状态改变的回调

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

  1. <template>
  2. <a-affix :offsetTop="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>

Affix固钉 - 图3

滚动容器

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

  1. <template>
  2. <div id="components-affix-demo-target" class="scrollable-container" ref="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>

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>