Skip to content

mpx.pageScrollTo(Object object)

将页面滚动到目标位置,支持选择器和滚动距离两种方式定位

支持情况: 微信、支付宝、RN、web

参考文档

参数

Object object

属性类型默认值必填说明最低版本支付宝webRN
scrollTopnumber滚动到页面的目标位置,单位 px
durationnumber300滚动动画的时长,单位 ms
selectorstring选择器2.7.3
offsetTopnumber偏移距离,需要和 selector 参数搭配使用,可以滚动到 selector 加偏移距离的位置,单位 px2.23.1
successfunction接口调用成功的回调函数
failfunction接口调用失败的回调函数
completefunction接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

使用 scrollTop 滚动到指定位置

js
mpx.pageScrollTo({
  scrollTop: 0,
  duration: 300
})

使用 selector 滚动到指定元素(小程序)

xml
<view id="target-section">目标区域</view>
js
mpx.pageScrollTo({
  selector: '#target-section',
  duration: 300
})

使用 scrollTop 滚动到顶部(React Native)

React Native 平台特殊说明

在 React Native 平台上使用 pageScrollTo 时,需要在页面的 scroll-view 组件上声明固定的 wx:ref="pageScrollView",框架将通过该固定 ref 定位滚动容器。

xml
<template>
  <view class="page">
    <!-- scroll-view 必须声明固定 ref 名称 pageScrollView -->
    <scroll-view wx:ref="pageScrollView" scroll-y="{{true}}" style="height: 100vh;">
      <view style="height: 500px;">顶部内容</view>
      <view style="height: 500px;">底部内容</view>
    </scroll-view>
  </view>
</template>

<script>
import { createPage } from '@mpxjs/core'

createPage({
  methods: {
    scrollToTop() {
      mpx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
    }
  }
})
</script>

使用 selector 滚动到指定元素(React Native)

xml
<template>
  <view class="page">
    <!-- scroll-view 必须声明固定 ref 名称 pageScrollView -->
    <scroll-view wx:ref="pageScrollView" scroll-y="{{true}}" style="height: 100vh;">
      <view style="height: 500px;">顶部内容</view>

      <!-- 目标元素需要同时添加 id 和 wx:ref -->
      <view id="target-section" wx:ref style="height: 200px;">
        目标区域
      </view>

      <view style="height: 500px;">底部内容</view>
    </scroll-view>
  </view>
</template>

<script>
import { createPage } from '@mpxjs/core'

createPage({
  methods: {
    scrollToTarget() {
      mpx.pageScrollTo({
        selector: '#target-section',
        duration: 300,
        offsetTop: 10,  // 可选:偏移 10px
        success: () => {
          console.log('滚动成功')
        },
        fail: (err) => {
          console.error('滚动失败:', err)
        }
      })
    }
  }
})
</script>

React Native 平台注意事项

必需的配置

  1. scroll-view 必须声明固定 ref 名称 pageScrollView
xml
<!-- ✅ 正确 -->
<scroll-view wx:ref="pageScrollView" scroll-y="{{true}}">
  <!-- 内容 -->
</scroll-view>

<!-- ❌ 错误:缺少 wx:ref="pageScrollView" -->
<scroll-view scroll-y="{{true}}">
  <!-- 内容 -->
</scroll-view>
  1. 使用 selector 时,目标元素必须同时有 id 和 wx:ref
xml
<!-- ✅ 正确:同时有 id 和 wx:ref -->
<view id="section-1" wx:ref>区域 1</view>

<!-- ❌ 错误:只有 id,没有 wx:ref -->
<view id="section-1">区域 1</view>
  1. 启用滚动方向
xml
<!-- ✅ 正确:启用纵向滚动 -->
<scroll-view scroll-y="{{true}}">

<!-- ❌ 错误:没有启用滚动 -->
<scroll-view>