效果
页面级 uni.pageScrollTo
官方文档:https://uniapp.dcloud.net.cn/api/ui/scroll.html#pagescrollto
原生头部导航
uni.pageScrollTo({selector: '#tabs',duration: 300
});
(推荐)需要兼容自定义头部导航
<template><view id="demo1" :style="{ height: '30vh', backgroundColor: 'red' }">A</view><viewid="demo2":style="{height: '50vh',backgroundColor: 'yellow'}"><button@click="onTop":style="{position: 'sticky',top: safeBottom + 'px'}">吸顶</button></view><view id="demo3" :style="{ height: '180vh', backgroundColor: 'green' }">C</view>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'const pageScrollTop = ref(0)
const safeBottom = ref(0)
onMounted(() => {const query = uni.createSelectorQuery()query.select('#demo2').boundingClientRect((data) => {const clientRect = uni.getMenuButtonBoundingClientRect()safeBottom.value = clientRect.bottompageScrollTop.value = Math.floor(data.top) - clientRect.bottom}).exec()
})function onTop() {uni.pageScrollTo({scrollTop: pageScrollTop.value, //滚动的距离duration: 10 //过渡时间})
}
</script></script>
微信是支持offsetTop
配置的,但是不知道为什么uni中未生效
不然可以写成下边的样子
uni.pageScrollTo({offsetTop: uni.getMenuButtonBoundingClientRect().bottom,selector: '#tabs',duration: 300
});
组件级 scroll-view
官方文档:https://uniapp.dcloud.net.cn/component/scroll-view.html
(推荐)scroll-top
<template><scroll-viewscroll-y="true":style="{ height: '100vh' }":scroll-top="scrollTop"><view id="demo1" :style="{ height: '30vh', backgroundColor: 'red' }">A</view><view id="demo2" :style="{ height: '50vh', backgroundColor: 'yellow' }"><button @click="onTop">吸顶</button></view><view id="demo3" :style="{ height: '180vh', backgroundColor: 'green' }">C</view></scroll-view>
</template><script setup lang="ts">
import { ref, onMounted } from 'vue'
const scrollTop = ref(0)
const initScrollTop = ref(0)onMounted(() => {const query = uni.createSelectorQuery()query.select('#demo2').boundingClientRect((data) => {if (!data) {return}const top = Math.floor(data.top)initScrollTop.value = top + 1 // 解决吸顶缝隙-模拟器有缝隙,真机没,保险起见}).exec()
})
function onTop() {if (scrollTop.value === initScrollTop.value) {scrollTop.value = initScrollTop.value + 0.1 // scrollTop新旧值的改变触发scroll-view的更新,否则不更新,} else {scrollTop.value = initScrollTop.value}
}
</script>
scroll-into-view
scroll-into-view 这个属性微信小程序无效。。抖音小程序生效
<template><scroll-viewscroll-y="true":style="{ height: '100vh' }":scroll-into-view="scrollIntoViewTarget"><view id="demo1" :style="{ height: '30vh', backgroundColor: 'red' }">A</view><view id="demo2" :style="{ height: '50vh', backgroundColor: 'yellow' }"><button @click="onTop">吸顶</button></view><view id="demo3" :style="{ height: '180vh', backgroundColor: 'green' }">C</view></scroll-view>
</template><script setup >
import { ref, nextTick } from 'vue'const scrollIntoViewTarget = ref(null)
function onTop() {scrollIntoViewTarget.value = nullnextTick(() => {scrollIntoViewTarget.value = 'demo2'})
}
</script>