微信小程序检测滚动到某元素位置的计算方法

wxml

html 复制代码
<!-- 这里我希望滚到9的底部的时候,也就是刚好划过9的时候出现一个按钮就是回到顶部的 -->
<view id="targetView">
    <view class="item" wx:for="{{arr}}" wx:key="index" style="width: 100%;height: 200rpx;margin-top: 20rpx;background-color: pink;">
        {{item}}
    </view>
</view>

<view wx:if="{{btnShow}}" bind:tap="scrollTargetViewInfo" style="position: fixed;bottom: 200rpx;right: 50rpx;background-color: blue;border-radius: 20rpx;padding:5rpx 20rpx;color: #ffffff;">回到顶部</view>

js

js 复制代码
Page({
    data: {
        arr: ['111', '222', '333', '444', '555', '666', '777', '888', '999', '101010', '111111', '121212', '131313', '141414'],
        btnShow: false, // 是否显示btn
        targetViewHeight: 0 // 目标 view 的高度
    },

    onLoad() {
        this.getTargetViewInfo();
    },

    // 获取目标 view 的位置和高度
    getTargetViewInfo() {
        const query = wx.createSelectorQuery();
        query.selectAll('.item').boundingClientRect((rect) => {
            if (rect[8]) {
                // 目标元素的上距离和自身高度减去一屏高度(因为滚动元素监听到的是滚出屏幕外的尺寸,因此这里要减去一屏)
                this.setData({
                    targetViewHeight: rect[8].top + rect[8].height - wx.getSystemInfoSync().windowHeight // 目标 view 的高度
                });
            }
        }).exec();
    },

    // 监听页面滚动事件
    onPageScroll(event) {
        const {
            scrollTop
        } = event;
        console.log('this.data.targetViewTop',this.data.targetViewHeight,scrollTop)
        // 判断是否滚动到目标 view 的底部
        if (scrollTop >= this.data.targetViewHeight) {
            this.setData({
                btnShow: true // 显示按钮
            });
        } else {
            this.setData({
                btnShow: false // 隐藏按钮
            });
        }
    },
    // 回到顶部
    scrollTargetViewInfo() {
        wx.pageScrollTo({
            scrollTop: 0, // 滚动到页面顶部
            duration: 300 // 滚动动画的时长,单位为 ms
        });
    }
});
相关推荐
m0_4628038826 分钟前
从信息管理视角看「按桌顺序分桌」:云分组优先分组的实现逻辑
微信小程序
爱折腾的编程老炮5 小时前
潮玩品牌自建抽盒机小程序——商城 + 抽盒 + 一番赏 + 会员 + 社区,一套代码怎么搭
spring boot·小程序·vue·mybatis·uniapp
新知图书6 小时前
第13章 从一句话需求到上线“续费管家”小程序
人工智能·小程序·智能体
数商云企14 小时前
2026年陕西软件开发首选数商云企AI微入口小程序定制方案
人工智能·小程序
bug总结21 小时前
uniapp 微信小程序分包规范
微信小程序·小程序·uni-app
Quor21 小时前
小程序工作室:AI 生成即运行的可视化工作台
人工智能·小程序
盟道科技1 天前
小程序电商订单超时自动取消的三种实现方案:定时扫描、Redis 过期监听、延迟消息对比与生产落地
数据库·redis·小程序
lhldsg1 天前
智慧场馆解决方案小程序系统:从架构设计到落地实践
java·小程序·需求分析
凉红茶1 天前
用Cursor开发微信小程序的第一天
微信小程序·小程序·ai编程
CRMEB系统商城1 天前
汽车养护连锁的数字化底座CRMEB 多门店系统实战方案
java·开发语言·小程序·开源·汽车