温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Vue监听滚动实现锚点定位(双向)示例

发布时间:2020-09-17 06:33:29 来源:脚本之家 阅读:1464 作者:乐夫天命兮 栏目:web开发

在项目需求中需要实现一个滚轴联动锚点的功能

效果图如下:

Vue监听滚动实现锚点定位(双向)示例

功能代码demo如下:

<template>
 <div class="container">
  <div class="wrapper">
   <div class="section"  v-for="(item, index) in list" :key="index" :>
    <div  :>{{item.name}}</div>
   </div>
  </div>
  <div id="nac" ></div>
  <nav >
  <a class="nav1" v-for="(item, index) in navList" :key="index" @click="jump(index)" :class="index==0?'current':''">{{item}}</a>
  </nav>
 </div>
</template>
<script>
 export default {
  data(){
   return {
    scroll: '',
    list: [{
    name: "第一条",
    backgroundcolor: "#90B2A3"
    }, {
    name: "第二条",
    backgroundcolor: "#A593B2"
    }, {
    name: "第三条",
    backgroundcolor: "#A7B293"
    }, {
    name: "第四条",
    backgroundcolor: "#0F2798"
    }, {
    name: "第五条",
    backgroundcolor: "#0A464D"
    }],
    navList: [1, 2, 3, 4, 5]
   }
  },
  methods: {
   dataScroll: function () {
    this.scroll = document.documentElement.scrollTop || document.body.scrollTop;
   },
   jump(index) {
    let jump = document.getElementsByClassName('section');
    // 获取需要滚动的距离
    let total = jump[index].offsetTop;
    // Chrome
    document.body.scrollTop = total;
    // Firefox
    document.documentElement.scrollTop = total;
    // Safari
    window.pageYOffset = total;
    // $('html, body').animate({
    // 'scrollTop': total
    // }, 400);
   },
   loadSroll: function () {
    var self = this;
    var $navs = $(".nav1");
    var sections = document.getElementsByClassName('section');
    for (var i = sections.length - 1; i >= 0; i--) {
     if (self.scroll >= sections[i].offsetTop - 100) {
      $navs.eq(i).addClass("current").siblings().removeClass("current")
      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>

以上这篇Vue监听滚动实现锚点定位(双向)示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI