Skip to content

mp-scroll-to 滚动到指定位置

指定何时出现(滚动到某个阈值,某个元素出现或消失)、点击滚动到指定位置(某个距离、某个元素)

TIP

若该组件不满足使用,可使用 useScrollTo 自行实现

代码演示

滚动到达某个阈值时显示

当页面滚动到距离顶部 200px 时显示,点击滚动回顶部(0px)

html
<mp-scroll-to :scroll-top="0" :visible-threshold="200" />

自定义位置和样式

按钮图标为向下(bottom),按钮悬浮在左边 30rpx 的位置,当页面滚动到距离顶部 200px 时显示,点击滚动到 250px 的位置

html
<mp-scroll-to
  icon="bottom"
  :scroll-top="250"
  :styles="{right: 'unset', left: '30rpx'}"
  :visible-threshold="-200"
/>

监听指定元素触达某个距离时显示(自定义 slot)

.card-5 滚动到触达 getNavbarHeight 的时候,悬浮按钮显示,滚动回顶部(0px)

html
<mp-scroll-to
  observe=".card-5"
  :observe-offset="{top: -device.getNavbarHeight()}"
  :scroll-top="0"
  :styles="{width: '100rpx', height: '100rpx'}"
>
  <image
    class="scroll-to-top-image"
    src="https://cloud-minapp-41176.cloud.ifanrusercontent.com/1qul9sK9mqJKqZr6.png"
  />
</mp-scroll-to>

滚动到指定元素

始终显示,当点击到时候滚动到 .card-12 距离顶部 getNavbarHeight 的位置。

html
<mp-scroll-to
  icon="bottom"
  :offset-top="-device.getNavbarHeight()"
  selector=".card-12"
  :styles="{right: 'unset', left: '30rpx'}"
  :visible-threshold="0"
>
</mp-scroll-to>

API

Props

Prop nameDescriptionTypeValuesDefault
visibleThreshold滚动阈值,可以接收负数。当阈值为正数时,表示当页面滚动位置大于等于阈值时元素显示,当阈值为负数时,表示当页面滚动位置小于等于阈值时元素显示。number-null
observe用于监听特定元素的选择器。如果提供该属性,将使用 IntersectionObserver.relativeToViewport 进行监听。详细信息请参阅:https://developers.weixin.qq.com/miniprogram/dev/api/wxml/IntersectionObserver.relativeToViewport.htmlstring-null
observeOffset必须与 observe 配套使用,指定 top 和 bottom 值,详细信息请参阅:https://developers.weixin.qq.com/miniprogram/dev/api/wxml/IntersectionObserver.relativeToViewport.htmlobject-null
scrollTop滚动到页面的目标位置,单位 px,参考:https://developers.weixin.qq.com/miniprogram/dev/api/ui/scroll/wx.pageScrollTo.htmlnumber-0
selector选择器,参考:https://developers.weixin.qq.com/miniprogram/dev/api/ui/scroll/wx.pageScrollTo.htmlstring-null
offsetTop偏移距离,需要和 selector 参数搭配使用,可以滚动到 selector 加偏移距离的位置,单位 px,参考:https://developers.weixin.qq.com/miniprogram/dev/api/ui/scroll/wx.pageScrollTo.htmlnumber-null
duration滚动动画的时长,单位 ms,参考:https://developers.weixin.qq.com/miniprogram/dev/api/ui/scroll/wx.pageScrollTo.htmlnumber-300
styles容器样式object-{}
icon箭头图标,支持 uni-icons 和网络图片string-'top'

Slots

NameDescriptionBindings
default自定义内容

源码

组件示例