VUE 实现滚动监听 导航栏置顶

版权声明:博客注明来源即可。 https://blog.csdn.net/u014027680/article/details/79291096

HTML

非重点的代码,比如样式啥的,我就不放上来了,一笔带过
简略的写一下html代码,可以对照文档最后的效果图看,应该不难理解


<div :style="{ paddingBottom: paddingBottom}">

    <header>资源信息</header>

    <div>
        <!-- 公司信息 浏览量 -->
    </div>

    <div id="fixedBar" :class="{ fixedBar: isFixed }">
        <!-- 品名 -->
        <!-- 规格 -->
        <!-- 产地 -->
        <!-- 单价 -->
    </div>

    <div :style="{ marginTop: marginTop }">
        <!-- 数据列表 -->
    </div>

    <footer class="footer">
        <button>订阅</button>
        <button>关闭</button>
        <div v-show="advertShow">
            <a @click="del">×</a>
            <img src="./广告.jpg" />
        </div>
    </footer>

</div>

<style>
    .fixedBar {
        position: fixed;
        top: 0;
        z-index: 999;
        width: 100%;
    }
</style>

VUE

1. data ()

data () {
    paddingBottom: '1.5rem', // 给最外层div一个padding-bottom
    // 因为footer是fixed定位 如果padding-bottom为0 数据列表拉到最下面的时候 会有部分数据被footer挡住

    isFixed: false, // bar浮动
    offsetTop: 0,   // 触发bar浮动的阈值
    marginTop: 0,   // 触发bar浮动的同时 给数据列表一个margin-top 防止列表突然上移 会很突兀

    advertShow: true, // 广告显示
}

2. mounted ()

mounted () {
    // 设置初始的 padding-bottom 值为 footer 的高度 +20 防止数据列表拉到最下面被footer挡住 +多少自定
    this.paddingBottom = document.querySelector('.footer').offsetHeight + 20 + 'px';

    // 设置bar浮动阈值为 #fixedBar 至页面顶部的距离
    this.offsetTop = document.querySelector('#fixedBar').offsetTop;

    // 开启滚动监听
    window.addEventListener('scroll', this.handleScroll);
}

3. methods

methods: {
    // 关闭广告
    del () {
        this.advertShow = true;
        this.$nextTick(() => {
            this.paddingBottom = document.querySelector('.footer').offsetHeight + 20 + 'px';
        });
    },

    // 滚动监听  滚动触发的效果写在这里
    handleScroll () {
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

        if (scrollTop >= this.offsetTop) {
            this.isFixed = true;
            this.marginTop = document.querySelector('#fixedBar').offsetHeight + 'px';
        } else {
            this.isFixed = false;
            this.marginTop = 0;
        }
    }
}

4. destroyed ()

destroyed () {
    window.removeEventListener('scroll', this.handleScroll); // 离开页面 关闭监听 不然会报错
}

效果图

页面效果
Bar Fixed 定位
数据列表没有被Footer挡住
关闭广告后没有出现大量空白

猜你喜欢

转载自blog.csdn.net/u014027680/article/details/79291096