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

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
        });
    }
});
相关推荐
2501_916007471 天前
iOS文件管理工具深度剖析,从系统沙盒到跨平台文件操作的多工具协同实践
android·macos·ios·小程序·uni-app·cocoa·iphone
wapchief1 天前
微信小程序camera相机帧转图片base64
微信小程序·小程序
QuantumLeap丶1 天前
《uni-app跨平台开发完全指南》- 05 - 基础组件使用
vue.js·微信小程序·uni-app
发财北1 天前
全屋智能家居定制小程序
小程序
2501_915918411 天前
Flutter 加固方案对比与实战,多工具组合的跨平台安全体系(Flutter App 加固/IPA 成品混淆/Ipa Guard CLI/自动化安全流程)
安全·flutter·ios·小程序·uni-app·自动化·iphone
泽_浪里白条1 天前
UniApp + Vue3 开发微信小程序数字人:TTS PCM 音频流与 SVGA 动画同步实战
微信小程序
小蒜学长1 天前
springboot基于Java的校园导航微信小程序的设计与实现(代码+数据库+LW)
java·spring boot·后端·微信小程序
说私域1 天前
定制开发AI智能名片S2B2C商城小程序的发展与整合资源策略研究
人工智能·小程序
WenGyyyL1 天前
微信小程序开发——第二章:微信小程序开发环境搭建
开发语言·python·微信小程序
TiAmo zhang1 天前
微信小程序开发案例 | 个人相册小程序(上)
微信小程序·小程序