<template>
    <div>
        <div class="menuBox">
            <button @click="scrollTo(25)">目录滚动到标题25</button>
            <br>
            <button @click="getScrollTop">获取目录内滚动条向下滚动的距离</button>
            <p>目录</p>
            <el-scrollbar ref="scrollMenuRef" class="scrollMenuBox">
                <p v-for="i in titleTotal" :key="i">标题{{i}}</p>
            </el-scrollbar>
        </div>
            <hr>
        <div class="add" @scroll="scrollContent">
                <div class="contentBox" ref="bodys">
                    <p v-for="i in rowTotal" :key="i">第{{i}}行</p>
                </div>
        </div>
    </div>
    
    
</template>
<script>
    export default {
        data() {
            return {
                // 总行数
                titleTotal: 150,
                // 总行数
                rowTotal: 200
            }
        },
        mounted() {
            // 监听浏览器/页面滚动条的滚动
                var bodys = this.$refs.bodys
            // bodys.addEventListener("scroll", this.scrollContent,true);
            // 监听el-scrollbar内滚动条的滚动
            
            this.$refs.scrollMenuRef.wrap.addEventListener("scroll", this.scrollMenu);
        },
        methods: {
            // el-scrollbar内滚动条滚动时，打印滚动条向下滚动的距离
            scrollMenu() {
                console.log(this.$refs.scrollMenuRef.wrap.scrollTop)
            },
// 页面滚动时触发
            scrollContent(e) {
                // scrollTop为显示屏顶部与整个文档顶部间的距离
                var scrollTop = e.target.scrollTop
                console.log(scrollTop);
                
                this.$refs.scrollMenuRef.wrap.scrollTop = scrollTop 
                
            },
            // el-scrollbar内滚动条滚动到指定的标题号
            scrollTo(titleNo) {
                this.$refs.scrollMenuRef.wrap.scrollTop = (titleNo - 1) / this.titleTotal * this.$refs.scrollMenuRef.wrap.scrollHeight
            },
            // 获取el-scrollbar内滚动条向下滚动的距离
            getScrollTop() {
                alert(this.$refs.scrollMenuRef.wrap.scrollTop)
            }
        },
    }
</script>
<style scoped>
    /*目录悬浮*/
    .menuBox {
        /* position: fixed; */
    }
 
    /*内容居中*/
    .contentBox {
        width: 60%;
        margin: auto;
    }
 .add{
     height: 400px;
     border: 1px solid red;
     position: relative;
     overflow: auto;
 }
    /*el-scrollbar 必须指定高度*/
    .scrollMenuBox {
        height: 200px;
        width: 100px;
        border: 1px solid red;
        .contentBox{
            position: absolute;
        }
    }
 
    /*隐藏水平滚动条*/
    /deep/ .el-scrollbar__wrap {
        overflow-x: hidden;
    }
</style>