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

发布于:2025-03-22 ⋅ 阅读:(15) ⋅ 点赞:(0)

wxml

<!-- 这里我希望滚到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

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
        });
    }
});