吸顶这个功能非常好实现只需要给页面元素设置下面这个就可以
.fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 999;
}
我这边想要的效果是我页面滚动一定距离后再吸顶
<view :class="{'fixed': isFixed}">
//吸顶的元素
{{item.title}}
</view>
onPageScroll(e) {
console.log("获取页面滚动距离", e)
this.scrollTop = e.scrollTop;
//当距离大于20的时候吸顶
if (this.scrollTop > 20) {
this.isFixed = true;
} else {
this.isFixed = false;
}
},
onLoad() {
},
之后我写了一个选项卡我想要点击选项卡滚动到选项卡指定的元素位置
<template>
<view class="content">
<view :class="{'fixed': isFixed}">
<scroll-view scroll-x="true" scroll-with-animation class="scroll-tab">
<block v-for="(item,index) in title" :key="index">
<view class="scroll-tab-item" :class="{'active': tabIndex==index}"
@tap="toggleTab(index,item.title)">
{{item.title}}
<view class="scroll-tab-line"></view>
</view>
</block>
</scroll-view>
</view>
<view class="text-area" style="height: 300rpx;" v-for="item in title" :id="item.title">
<text class="title">{{item.title}}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
isFixed: false, // 是否固定在页面顶部
scrollTop: 0, // 页面滚动距离
tabIndex: 0,
title: [{
title: '哈哈1'
}, {
title: '哈哈2'
}, {
title: '哈哈3'
}, {
title: '哈哈4'
}, {
title: '哈哈5'
}, {
title: '哈哈6'
}, {
title: '哈哈7'
}, {
title: '哈哈81'
}, ]
}
},
onPageScroll(e) {
console.log("获取页面滚动距离", e)
this.scrollTop = e.scrollTop;
//当距离大于20的时候吸顶
if (this.scrollTop > 20) {
this.isFixed = true;
} else {
this.isFixed = false;
}
},
onLoad() {
},
methods: {
//切换选项卡
toggleTab(index, id) {
console.log(id)
this.tabIndex = index;
uni.pageScrollTo({
selector: "#" + id,
duration: 300,
success() {
console.log("成功")
}
})
},
}
}
</script>
<style>
.fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 999;
}
.scroll-tab {
white-space: nowrap;
/* 必要,导航栏才能横向*/
border-bottom: 1rpx solid #eee;
text-align: center;
}
.scroll-tab-item {
display: inline-block;
/* 必要,导航栏才能横向*/
margin: 20rpx 30rpx 0 30rpx;
}
.active .scroll-tab-line {
border-bottom: 5rpx solid red;
border-top: 5rpx solid red;
border-radius: 20rpx;
width: 70rpx;
}
</style>