當(dāng)在scroll-view中使用sticky元素時(shí) 為確保其正常響應(yīng)滾動(dòng)效果 需要在scroll-view內(nèi)部添加一個(gè)無樣式的view元素 作為所有內(nèi)容的根元素 這樣即使sticky元素超出了scroll-view的原始高度 它也能正確地識(shí)別與頂部的相對(duì)位置 保持其應(yīng)有的樣式和交互效果
<template>
<view class="content">
<scroll-view scroll-y="true" class="scroll-view">
<view>
<view class="header">
我是固定標(biāo)題
</view>
<view class="body">
我是內(nèi)容
</view>
<view class="line">
我是父元素高度
</view>
</view>
</scroll-view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello',
};
},
onLoad() {},
methods: {}
};
</script>
<style lang="scss" scoped>
.scroll-view {
height: 100vw;
/* overflow-y: auto; */
position: relative;
color: #fff;
text-align: center;
.header {
background-color: red;
height: 80rpx;
line-height: 80rpx;
position: sticky;
top: 0rpx;
}
.body {
background-color: green;
height: 800vh;
}
.line {
position: absolute;
top: 0;
height: 100%;
background-color: royalblue;
z-index: 2;
}
}
</style>

image.png
方法是在scroll-view中添加一個(gè)父級(jí)容器,這樣可以使用position: sticky根據(jù)新添加的父級(jí)容器高度來實(shí)現(xiàn)吸附效果,而不是根據(jù)scroll-view的滾動(dòng)高度。這是一個(gè)很好的解決方案,可以避免在scroll-view中使用position: fixed的問題。