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

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
        });
    }
});
相关推荐
蜗牛前端2 天前
codex 全流程开发上线的高颜值礼簿小程序
前端·微信小程序
爱勇宝5 天前
我想认真做一件小事:让孩子和家长更好地互动
微信小程序·小程序·云开发
唯火锅不可辜负6 天前
避坑指南:iOS 下 scroll-view 嵌套 fixed 布局的“翻车”现场与修复
微信小程序
didiplus6 天前
运维人的随身神器:我把25个常用工具塞进了微信小程序
微信小程序
一份执念6 天前
uni-app 小程序分包限制处理与主包体积优化实战
前端·微信小程序
一份执念6 天前
ECharts 安装与使用完全指南:从全量引入到小程序分包优化
微信小程序·echarts
skiyee7 天前
🔥UniApp 仅需 5 行代码!实现所有页面中控制应用主题变化
前端·微信小程序
Jinkey9 天前
要用户手机号真的是为了打骚扰电话吗?浅谈微信生态会员账号体系与资产合并
后端·微信·微信小程序
用户43242810611411 天前
微信小程序从0到1接入微信支付的完整攻略
微信小程序
spmcor13 天前
微信小程序 setStorageSync 踩坑实录:别让"顺手一存"变成"隐形炸弹"
微信小程序