技术栈

vue实现平滑过渡返回顶部、滚动界限值隐藏元素

Vue,JavaScript

Dom部分

<!--底部固定TAB-->
<transition name="fade">
    <van-tabbar v-show="tabShowFlag" route active-color="#009dd9"  @change="tabChange">
        <van-tabbar-item replace to="/rec" name="rec" icon="medal">推荐</van-tabbar-item>
        <van-tabbar-item replace to="/career" name="career" icon="coupon">职位</van-tabbar-item>
        <van-tabbar-item replace to="/time" name="time" icon="invition">投递</van-tabbar-item>
        <van-tabbar-item replace to="/mine" name="mine" icon="manager">我的</van-tabbar-item>
    </van-tabbar>
</transition>

<!--返回顶部-->
<transition name="fade">
    <div id="back-top" v-show="backTopFlag" @click="backTop">
        <i class="fa fa-arrow-up"/>
    </div>
</transition>

Js部分

data() {

    return {
        tabShowFlag: true,
        backTopFlag: false,
    }
},
created() {

    //滚动识别
    this.spaScroll((direction, nowPos) => {

        //TAB显性
        switch (direction) {
            case 'up': {
                this.tabShowFlag = true;
                break;
            }
            case 'down': {
                if(nowPos > 700) {
                    this.tabShowFlag = false;
                }
                break;
            }
        }

        //返回顶部
        this.backTopFlag = nowPos > 200;
    });
},
methods: {

    //单页面应用滚动识别
    spaScroll(fn) {

        let beforeScrollTop = document.documentElement.scrollTop || document.body.scrollTop;

        fn = fn || function() {};

        window.addEventListener('scroll',() => {

            let afterScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            let delta = afterScrollTop - beforeScrollTop;

            if( delta === 0 ) return false;
            fn( delta > 0 ? 'down' : 'up', afterScrollTop);
            beforeScrollTop = afterScrollTop;
        });
    },

    //返回顶部
    backTop() {

        let nowPos = document.documentElement.scrollTop;

        const timeTop = setInterval(() => {

            document.documentElement.scrollTop = nowPos -= 20;
            if(nowPos <= 0) {
                clearInterval(timeTop);
            }
        }, 10);
    },
}
点我评论
打赏本文
二维码


55

文章

22

标签