当前位置: 首页 > 文档资料 > Vant 中文文档 >

Sticky 粘性布局

优质
小牛编辑
117浏览
2023-12-01

介绍

Sticky 组件与 CSS 中position: sticky属性实现的效果一致,当组件在屏幕范围内时,会按照正常的布局排列,当组件滚出屏幕范围时,始终会固定在屏幕顶部。

引入

import { createApp } from 'vue';
import { Sticky } from 'vant';

const app = createApp();
app.use(Sticky);

代码演示

基础用法

将内容包裹在 Sticky 组件内即可。

<van-sticky>
  <van-button type="primary">基础用法</van-button>
</van-sticky>

吸顶距离

通过 offset-top 属性可以设置组件在吸顶时与顶部的距离。

<van-sticky :offset-top="50">
  <van-button type="primary">吸顶距离</van-button>
</van-sticky>

指定容器

通过 container 属性可以指定组件的容器,页面滚动时,组件会始终保持在容器范围内,当组件即将超出容器底部时,会固定在容器的底部。

<div ref="container" style="height: 150px;">
  <van-sticky :container="container">
    <van-button type="warning">指定容器</van-button>
  </van-sticky>
</div>
export default {
  data() {
    return {
      container: null,
    };
  },
  mounted() {
    this.container = this.$refs.container;
  },
};

API

Props

参数说明类型默认值
offset-top v2.8.7吸顶时与顶部的距离,支持 px vw rem 单位,默认 pxnumber / string0
z-index吸顶时的 z-indexnumber / string99
container容器对应的 HTML 节点Element-

Events

事件名说明回调参数
scroll滚动时触发{ scrollTop: 距离顶部位置, isFixed: 是否吸顶 }