<template>
    <nav style="width: 100%" :class="scrollFixed? 'isFixed' :''" :style="{top:scrollFixed? (offset+'px'):0}">
        <slot></slot>
    </nav>
</template>

<script>
    export default {
        name: "lj-sticky",
        props: {
            offset: {
                type: Number,
                default: 0
            }
        },
        data() {
            return {
                scrollFixed: false,
                offsetTop: 0
            }
        },
        methods: {
            windowScroll() {
                // 滚动条顶部 距 滚动原点的高度
                let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
                /**
                 * 两个高度比较
                 * 如果滑动距离 > 吸顶元素到页面顶端距离  动态添加
                 * scrollTop === 0时，页面回到顶部
                 */
                let newFixed = scrollTop >= this.offsetTop && scrollTop > 0;
                if (this.scrollFixed !== newFixed) {
                    this.scrollFixed = newFixed;
                    if (newFixed) {
                        this.$emit("sticky-on");
                    } else {
                        this.$emit("sticky-off");
                    }
                }

            }
        },
        mounted() {
            // 需吸顶元素 距 离浏览器顶端的高度
            this.offsetTop = this.$el.offsetTop;
            // 滚动监听
            window.addEventListener('scroll', this.windowScroll);
        },
        destroyed() {
            // 关闭 销毁监听
            window.removeEventListener('scroll', this.windowScroll);
        }
    }
</script>

<style scoped>
    .isFixed {
        position: fixed;
        /*left: 0;*/
        z-index: 999;
        /*background: #12d168;*/
        transition: all 0.2s;
        /*color: #7511ff;*/
    }
</style>