<template>
 <div class="container">
  <div class="wrapper">
   <div class="section" style="height:385px;width:100%" v-for="(item, index) in list" :key="index" >
    <div style="width:100%;height:100%;font-size:30px;text-align:center;font-weight:bold;color:#fff;" :style="{'background':item.backgroundcolor}">{{item.name}}</div>
   </div>
  </div>
  <!-- <div id="nac" style="height:200px;"></div> -->
  <nav style="position:fixed;right:30px;top:300px;">
  <a class="nav1" v-for="(item, index) in navList" :key="index" @click="jump(index)" :class="index==tabindex?'current':''">{{item}}</a>
  </nav>
 </div>
</template>
<script>
    export default {
        data(){
        return {
            scroll: '',
            list: [{
                name: "第一条1",
                backgroundcolor: "#90B2A3"
            }, {
                name: "第二条",
                backgroundcolor: "#A593B2"
            }, {
                name: "第三条",
                backgroundcolor: "#A7B293"
            }, {
                name: "第四条",
                backgroundcolor: "#0F2798"
            }, {
                name: "第五条",
                backgroundcolor: "#0A464D"
            }],
            navList: [1, 2, 3, 4, 5],
            tabindex : 0
        }
        },
        methods: {
            dataScroll: function () {
                this.scroll = document.documentElement.scrollTop || document.body.scrollTop;
            },
            jump(index) {
                let jump = document.getElementsByClassName('section');
                // 获取需要滚动的距离
                let total = jump[index].offsetTop -  80;
                // Chrome
                document.body.scrollTop = total;
                // Firefox
                document.documentElement.scrollTop = total;
                // Safari
                window.pageYOffset = total;
                this.tabindex = index;
            },
            loadSroll: function () {
                var self = this;
                var sections = document.getElementsByClassName('section');
                for (var i = sections.length - 1; i >= 0; i--) {
                    if (self.scroll >= sections[i].offsetTop - 100) {
                        this.tabindex = i;
                        break;
                    }
                }
            }
        },
        watch: {
        scroll: function () {
            this.loadSroll()
        }
        },
        mounted() {
        window.addEventListener('scroll', this.dataScroll);
        }
    }
</script>

<style>
 * {
 padding: 0;
 margin: 0;
 }
 .nav1 {
  display: block;
  width: 40px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  background: #eee;
  margin: 10px 0;
 }
 .current {
  color: #fff;
  background: red;
 }
</style>

以上代码最后一项滚动监听不灵敏,不知各位大神是否有更好的办法

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐