Affix 固钉
将页面元素固定在特定可视区域。
ts
import { createApp } from 'vue'
import { Affix as ElAffix } from '@szhn/dh-design-pc'
const app = createApp()
app.use(ElAffix)基础用法
固钉默认固定在页面顶部,通过 offset 属性调整吸顶距离,默认值为 0。
<template>
<div class="demo-affix">
<el-affix :offset="120">
<el-button type="primary">固定在距顶部 120px 处</el-button>
</el-affix>
</div>
</template>
<script lang="ts" setup>
import { Affix as ElAffix, Button as ElButton } from '@szhn/dh-design-pc'
</script>
<style scoped>
.demo-affix {
height: 100px;
overflow: hidden;
}
</style>指定容器
通过设置 target 属性,让固钉始终保持在容器内,超过范围则隐藏。请注意容器避免出现滚动条。
<template>
<div class="affix-target-wrap" id="affix-target-wrap">
<div class="placeholder">向下滚动查看效果</div>
<el-affix target="#affix-target-wrap" :offset="20">
<el-button type="primary">指定容器内的固钉</el-button>
</el-affix>
<div class="tall">容器内部区域</div>
</div>
</template>
<script lang="ts" setup>
import { Affix as ElAffix, Button as ElButton } from '@szhn/dh-design-pc'
</script>
<style scoped>
.affix-target-wrap {
height: 200px;
overflow: auto;
padding: 12px;
border: 1px solid var(--el-border-color-lighter);
border-radius: var(--el-border-radius-base);
background: var(--el-fill-color-light);
}
.placeholder {
color: var(--el-text-color-regular);
margin-bottom: 12px;
}
.tall {
height: 400px;
margin-top: 20px;
color: var(--el-text-color-regular);
}
</style>固定位置
Affix 组件提供 top 和 bottom 两种固定位置,通过 position 属性切换,默认值为 top。
<template>
<div class="demo-affix-position">
<el-affix position="bottom" :offset="20">
<el-button type="primary">固定在距底部 20px 处</el-button>
</el-affix>
</div>
</template>
<script lang="ts" setup>
import { Affix as ElAffix, Button as ElButton } from '@szhn/dh-design-pc'
</script>
<style scoped>
.demo-affix-position {
height: 100px;
}
</style>监听状态变化
通过 change 事件可以在固钉的固定状态改变时得到通知。
<template>
<div>
<el-affix :offset="120" @change="onChange">
<el-button :type="fixed ? 'success' : 'primary'">
当前状态:{{ fixed ? '已固定' : '未固定' }}
</el-button>
</el-affix>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { Affix as ElAffix, Button as ElButton } from '@szhn/dh-design-pc'
const fixed = ref(false)
function onChange(val: boolean) {
fixed.value = val
}
</script>API
Affix Attributes
| 属性名 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| offset | 偏移距离 | number | 0 |
| position | 固钉位置 | top | bottom | top |
| target | 指定容器(CSS 选择器) | string | — |
| z-index | z-index 层级 | number | 100 |
Affix Events
| 事件名 | 说明 | 参数 |
|---|---|---|
| change | 固钉状态改变时触发 | (fixed: boolean) |
| scroll | 滚动时触发 | ({ scrollTop, fixed }) |
Affix Slots
| 插槽名 | 说明 |
|---|---|
| default | 自定义默认内容 |
更多示例请参考 Element Plus Affix 文档。
