核心组件:通过scroll-view
组件和scroll-into-view
属性实现
{{item}} 跳转第一节 跳转第二节
Page({ data: { toView: '' }, jumpTo(e) { const targetId = e.currentTarget.dataset.id; this.setData({ toView: targetId }) // 通过修改scroll-into-view值触发滚动 } })
Page({ onLoad() { // 延时3秒后跳转至首页[6](@ref) setTimeout(() => { wx.reLaunch({ url: '/pages/home/index' }) }, 3000) } })
onLoad(options) { if(options.anchor) { // 通过URL参数触发锚点 this.setData({ toView: options.anchor }) } }
使用API动态计算位置
// 获取目标元素位置并滚动 function scrollToElement(selector) { const query = wx.createSelectorQuery() query.select(selector).boundingClientRect() query.selectViewport().scrollOffset() query.exec(res => { wx.pageScrollTo({ scrollTop: res[0].top + res[1].scrollTop, duration: 300 }) }) }
Page({ data: { autoScrollId: '' }, // 页面加载完成自动定位 onReady() { if(this.data.autoScrollId) { this.scrollToElement('#' + this.data.autoScrollId) } }, // 点击事件处理 handleTap(e) { const id = e.currentTarget.dataset.id this.scrollToElement('#' + id) } })
{{item.title}}