微信小程序和 Vue 实现指定元素吸顶效果

流氓凡 技术分享 2020-07-11 7.57 K 0
// 监听页面滚动事件
    onPageScroll() {
        let _this = this;
        // 获取需要吸顶的元素距离顶部的高度
        const query = wx.createSelectorQuery();
        // 需要监听的吸顶元素goods-list-box
        query.select('.goods-list-box').boundingClientRect(function (res) {
            if (res.top <= 0) {
                _this.setData({
                    tabFix: 'Fixed'
                })
            } else {
                _this.setData({
                    tabFix: ''
                })
            }
        }).exec();
    },


css 样式

.Fixed{
  position: fixed;
  top: 0;
  margin-top: 0;
  z-index: 99999;
  background: #fff;
  box-shadow: 0 0 10px #ddd;
  margin-left: -16rpx;
}


wxml

<view class="goods-list-box">
        <scroll-view class="menu-item-scroll {{tabFix}} clearfix" scroll-x> </scroll-view>
</view>


Vue 指定元素吸顶效果实现

在 mounted 方法中监听页面滚动

window.addEventListener('scroll', this.windowScroll);

在刚才定义的windowScroll方法中监听元素距离和当前距离,这里我监听的是 goods-list-box 类元素

// 监听页面滚动距离和元素距顶部距离
            windowScroll() {
                let _this = this;
                // 获取元素距离顶部
                let offsetTop = document.querySelector('.goods-list-box').offsetTop;
                let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
                if (scrollTop >= offsetTop) {
                    _this.tabFix = true;
                } else {
                    _this.tabFix = false;
                }
            },

css 样式

.Fixed{
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        margin-top: 0;
        z-index: 9999;
        background: #fff;
        box-shadow: 0 0 10px #ddd;
        overflow-x: auto;
    }

在需要吸顶的元素外边套一个 div(此方法可解决 fixed 定位后无法横向滚动问题)

<div :class="[tabFix ? 'Fixed' :'']">
    <!-- 需要吸顶的导航栏 -->
</div>

当前,提示 tabFix 未定义的话就去 data 中声明一个吧

tabFix: '',


评论