el-affix
是 Element Plus
框架中的固钉组件,用于将元素固定在页面的某个位置,常用于导航栏、返回顶部按钮等场景。
el-affix
属性详解
-
offset-top:
- 类型:
Number
- 用途: 元素距离顶部的距离。
- 默认值:
0
- 类型:
-
offset-bottom:
- 类型:
Number
- 用途: 元素距离底部的距离。
- 默认值:
0
- 类型:
-
target:
- 类型:
String | HTMLElement
- 用途: 固定的目标容器,默认为
window
。 - 默认值:
window
- 类型:
-
z-index:
- 类型:
Number
- 用途: 固定元素的 z-index。
- 默认值:
100
- 类型:
-
position:
- 类型:
String
- 用途: 固定元素的位置,可选值为
fixed
或absolute
。 - 默认值:
fixed
- 类型:
el-affix
事件详解
-
change:
- 类型:
Function
- 用途: 固定状态发生变化时触发。
- 参数:
fixed
(布尔值,表示是否固定)
- 类型:
el-affix
插槽详解
-
default:
- 插槽名称:
default
- 用途: 自定义固定元素的内容。
- 插槽名称:
完整示例代码
<template>
<div>
<h2>Affix 示例</h2>
<!-- 基本用法 -->
<el-affix :offset-top="100">
<el-button type="primary">固定在顶部</el-button>
</el-affix>
<!-- 固定在底部 -->
<el-affix :offset-bottom="50">
<el-button type="success">固定在底部</el-button>
</el-affix>
<!-- 自定义目标容器 -->
<div id="custom-container" style="height: 500px; border: 1px solid #ccc;">
<el-affix :target="'#custom-container'" :offset-top="50">
<el-button type="warning">固定在自定义容器顶部</el-button>
</el-affix>
</div>
<!-- 自定义 z-index 和位置 -->
<el-affix :offset-top="100" :z-index="200" position="absolute">
<el-button type="info">绝对定位,z-index 为 200</el-button>
</el-affix>
<!-- 监听固定状态变化 -->
<el-affix :offset-top="100" @change="handleChange">
<el-button type="primary">监听固定状态变化</el-button>
</el-affix>
</div>
</template>
<script setup>
import { ElMessage } from 'element-plus'
const handleChange = (fixed) => {
if (fixed) {
ElMessage({
message: '元素已固定',
type: 'success'
})
} else {
ElMessage({
message: '元素已取消固定',
type: 'info'
})
}
}
</script>
代码解释
-
基本用法:
- 使用
el-affix
组件并设置offset-top
属性来指定元素距离顶部的距离。 -
<el-affix :offset-top="100"> <el-button type="primary">固定在顶部</el-button> </el-affix>
- 使用
-
固定在底部:
- 使用
offset-bottom
属性来指定元素距离底部的距离。 -
<el-affix :offset-bottom="50"> <el-button type="success">固定在底部</el-button> </el-affix>
- 使用
-
自定义目标容器:
- 使用
target
属性指定固定的容器。 -
<div id="custom-container" style="height: 500px; border: 1px solid #ccc;"> <el-affix :target="'#custom-container'" :offset-top="50"> <el-button type="warning">固定在自定义容器顶部</el-button> </el-affix> </div>
- 使用
-
自定义 z-index 和位置:
- 使用
z-index
和position
属性自定义固定元素的 z-index 和位置。 -
<el-affix :offset-top="100" :z-index="200" position="absolute"> <el-button type="info">绝对定位,z-index 为 200</el-button> </el-affix>
- 使用
-
监听固定状态变化:
- 使用
@change
事件监听固定状态的变化。 -
<el-affix :offset-top="100" @change="handleChange"> <el-button type="primary">监听固定状态变化</el-button> </el-affix>
- 使用