第一种:

<template>
  <view>
    <view class="anchor" id="anchor1">锚点1</view>
    <view class="anchor" id="anchor2">锚点2</view>
    <view class="anchor" id="anchor3">锚点3</view>
    <!-- 更多锚点 -->
    <button @click="scrollToAnchor('anchor1')">跳转到锚点1</button>
    <button @click="scrollToAnchor('anchor2')">跳转到锚点2</button>
    <button @click="scrollToAnchor('anchor3')">跳转到锚点3</button>
  </view>
</template>
 
<script>
export default {
  methods: {
    scrollToAnchor(anchor) {
      const query = uni.createSelectorQuery().in(this);
      query.select('#' + anchor).boundingClientRect(data => {
//const index = res.findIndex((rect)=>{
//return rect.top > rect.height
//})
        if (data) {
          uni.pageScrollTo({
            scrollTop: data.top + (pageScrollTop || 0),
            duration: 300 // 动画时长,默认300ms
          });
        }
      }).exec();
    }
  }
}
</script>
 
<style>
.anchor {
  height: 500px;
  background-color: #f0f0f0;
  margin-bottom: 20px;
}
</style>

第二种:
代码用

<scroll-view scroll-y="true" style="height: 300px;" scroll-into-view="{{toView}}" scroll-with-animation="true">
  <view id="a" style="height:100px;">A</view>
  <view id="b" style="height:100px;">B</view>
  <view id="c" style="height:100px;">C</view>
  <view id="d" style="height:100px;">D</view>
  <view id="e" style="height:100px;">E</view>
</scroll-view>
<button bindtap="scrollToA">跳转到A</button>
<button bindtap="scrollToB">跳转到B</button>
Page({
  data: {
    toView: 'a'
  },
  scrollToA: function() {
    this.setData({ toView: 'a' });
  },
  scrollToB: function() {
    this.setData({ toView: 'b' });
  }
})

史晶晶
78 声望3 粉丝

菜鸟爱学习