欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

监听滚动事件 实现动态锚点

程序员文章站 2024-01-23 12:16:52
...

前几天做项目的时候,需要实现一个动态锚点的效果

监听滚动事件 实现动态锚点

如果是传统项目,这个效果就非常简单。但是放到 Vue 中,就有两大难题:

1. 在没有 jQuery 的 animate() 方法的情况下,如何实现平滑滚动?

2. 如何监听页面滚动事件?

在浏览了大量文章、进行多次尝试之后,终于解决了这些问题

期间主要涉及到了 setTimeout 的递归用法,和 Vue 生命周期中的 mounted

 

一、锚点实现

在实现平滑滚动之前,得先确保基本的锚点功能

如果没有其他要求,直接用 <a href="#id"> 是最简单粗暴的办法

但是为了满足后续的要求,必须另外想办法

 

首先在父组件(表单)中添加 class="d_jump" 作为钩子

监听滚动事件 实现动态锚点

然后在子组件中添加一个 jump 方法

监听滚动事件 实现动态锚点

 

jump (index) {
    let jump = document.querySelectorAll('.d_jump')
    // 获取需要滚动的距离
    let total = jump[index].offsetTop
    // Chrome
    document.body.scrollTop = total
    // Firefox
    document.documentElement.scrollTop = total
    // Safari
    window.pageYOffset = total
},

通过 offsetTop 获取对象到窗体顶部的距离,然后赋值给 scrollTop,就能实现锚点的功能

需要注意的是,各浏览器下获取 scrollTop 有所差异

Chrome: document.body.scrollTop

Firefox: document.documentElement.scrollTop

 

二、平滑滚动

仅仅是锚点是不够的,这样的跳转十分突兀

为了更好的用户体验 ,需要将滚动的过程展现出来

如果有 jQuery 实现平滑滚动就非常简单:

$('html body').animate({scrollTop: total}, 500);

可惜没如果~~

在看了好些文章之后,有了一个大概的开发思路:

将总距离分成很多小段,然后每隔一段时间跳一段

只要每段的时间足够短,频次足够多,在视觉上就是正常的平滑滚动了

 

// 平滑滚动,时长500ms,每10ms一跳,共50跳
// 获取当前滚动条与窗体顶部的距离
let distance = document.documentElement.scrollTop || document.body.scrollTop
// 计算每一小段的距离
let step = total / 50
(function smoothDown () {
  if (distance < total) {
    distance += step
  // 移动一小段
    document.body.scrollTop = distance
    document.documentElement.scrollTop = distance
  // 设定每一次跳动的时间间隔为10ms
    setTimeout(smoothDown, 10)
  } else {
  // 限制滚动停止时的距离
    document.body.scrollTop = total
    document.documentElement.scrollTop = total
  }
})()

 

实际情况下,得考虑向上滚动和向下滚动两种情况,完整的代码为:

    jump (index) {
        // 用 class="d_jump" 添加锚点
        let jump = document.querySelectorAll('.d_jump')
        let total = jump[index].offsetTop
        let distance = document.documentElement.scrollTop || document.body.scrollTop
        // 平滑滚动,时长500ms,每10ms一跳,共50跳
        let step = total / 50
        if (total > distance) {
          smoothDown()
        } else {
          let newTotal = distance - total
          step = newTotal / 50
          smoothUp()
        }
        function smoothDown () {
          if (distance < total) {
            distance += step
       document.body.scrollTop = distance
            document.documentElement.scrollTop = distance
            setTimeout(smoothDown, 10)
          } else {
            document.body.scrollTop = total
            document.documentElement.scrollTop = total
          }
        }
        function smoothUp () {
          if (distance > total) {
            distance -= step
       document.body.scrollTop = distance
            document.documentElement.scrollTop = distance
            setTimeout(smoothUp, 10)
          } else {
            document.body.scrollTop = total
            document.documentElement.scrollTop = total
          }
       } 
     }

 

三、修改锚点状态

在上面展示的效果中,当页面滚动的时候,锚点的**状态会有相应的改变

其实这个效果并不难,只需要监听页面滚动事件,然后根据滚动条的距离修改锚点状态就可以了

但是在 Vue 中,应该在什么地方监听滚动事件呢?

  mounted: function () {
    this.$nextTick(function () {
      window.addEventListener('scroll', this.onScroll)
    })
  },
  methods: {
    onScroll () {
      let scrolled = document.documentElement.scrollTop || document.body.scrollTop
    // 586、1063分别为第二个和第三个锚点对应的距离
      if (scrolled >= 1063) {
        this.steps.active = 2
      } else if (scrolled < 1063 && scrolled >= 586) {
        this.steps.active = 1
      } else {
        this.steps.active = 0
      }
    }
  }

上面的代码中,我先写了一个修改锚点状态的方法 onScroll,然后在 mounted 中监听 scroll 事件,并执行 onScroll 方法

mounted 是 Vue 生命周期中的一个状态,在这个状态下,$el (vue 实例的根元素)已经创建完毕,但还没有加载数据

从结果上看,也可以在 created 状态下监听 scroll 事件

如果对 mounted 和 created 还不够了解,可以参考官方文档·生命周期图示

根据以上实现原理,做的另一种业务需求:

监听滚动事件 实现动态锚点

代码如下

<template>
  <div class="app-container">
    <div class="content">
      <div>
        <div class="content-fixed">
          <!-- <div class="content-head-top"></div> -->
          <div class="content-head relative">
            <div class="paper-title">【{{ Tittle }}】详情预览</div>
            <div class="img-close-btn" @click="CallBack" title="返回"></div>
          </div>
        </div>
        <div class="content-body relative mat-64">
          <div class="question-total-box-outer">
            <div class="question-total-box inline-block">
              <div class="question-total-title">本次选题列表</div>
              <div class="question-total-body text-left" v-for="(TypeData, index) in QuestionTypeData" :key="TypeData.QuestionTypeId">
                <div>{{ TypeData.QuestionType }}
                  <!-- <div class="bag-delete-icon"></div> -->
                </div>
                <ul class="ul-left mat-10 mab-10">
                  <li v-for="Data in PracticeDetailsData" :key="Data.Id" v-if="TypeData.QuestionTypeId==Data.QuestionTypeId" @click="listClick">
                    <a :indexID="Data.QuestionNumber + index + 1">{{Data.QuestionNumber}}</a>
                  </li>
                </ul>
              </div>
              <!-- <div class="question-total-foot">
                                <div class="add-paper-btn inline-block"><img src="" alt=""> 继续选题
                                </div>
                            </div> -->
              <!-- <div class="btn-default btn-bag">
                                <div class="icon-publish"></div>
                                发布作业
                            </div> -->
            </div>
          </div>
          <!-- <div class="question-box" v-for="(Data, index) in PracticeDetailsData" :key="Data.ID"> -->
          <div class="question-box" v-for="TypeData in QuestionTypeData" :key="TypeData.QuestionTypeId">
            <div class="paper-type d_jump" :typeId="TypeData.QuestionTypeId" style="margin-top: 10px;">{{ TypeData.QuestionTypeName }}</div>
            <div class="d_jump" v-for="Data in PracticeDetailsData" :key="Data.Id" v-if="TypeData.QuestionTypeId==Data.QuestionTypeId">
              <div class="question mat-10" :id="Data.Id">
                <div class="quesiton-head">
                  <div class="float-left">题目编号:{{Data.Id}}</div>
                  <ul class="float-right question-head-ul">
                    <li>题型:{{Data.QuestionType}}</li>
                    <li>|</li>
                    <li>难度:{{Data.DifficultyContext}}</li>
                    <li>|</li>
                    <li>分值:{{Data.Score}}分</li>
                    <li><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyFpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTQyIDc5LjE2MDkyNCwgMjAxNy8wNy8xMy0wMTowNjozOSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChXaW5kb3dzKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpDQzE2QkY3REZCRUQxMUU3OUY2OEQ4REI0RURCQzhCMSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpDQzE2QkY3RUZCRUQxMUU3OUY2OEQ4REI0RURCQzhCMSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkNDMTZCRjdCRkJFRDExRTc5RjY4RDhEQjRFREJDOEIxIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkNDMTZCRjdDRkJFRDExRTc5RjY4RDhEQjRFREJDOEIxIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+syyu7gAAAWlJREFUeNp0UstKw1AQnZuklLYxEkiyyLb4+JjqRv0A3Qvil6i41R8QNwX/pUjqB6QpgUgCsU3inEumxFAPDDe5nHNn5syopmlIsFwuPT7uOWYcx+31gmPO8TSdThPhKhGy6EIp9TKZTA7H4zENBgN9v9lsqCgKyvM8Y+4Ni993QohM03zzPE/xSVmWaQEwGo3Itm39nyRJU1XVFcQqiiKfM0VBEDjIUpYlrVYrGg6HmlzXNTmOowP/cRwj85HBj95yeY6UhoxhGJLv++S6rr7DYwA44PLnHYTn6ElgWRYZhrHrD0B2QcudgXEq2bpgM3SvnEGXKWi5JwbtwXa7pTRNtTFSbg8/EC6kJAE7p0+42UfL/YJwjjl1gZ5gDozqo+V+QPiM4XazotT1eq2jnw1c/nwweJgxNgLDFTGcldl1ReC02xN3V+6SF+GVXTz4Z+W+mXv9Z+X2LPkZLId7HJ/oieOxu+S/AgwAzajHtDwIKkYAAAAASUVORK5CYII=" alt=""></li>
                  </ul>
                </div>
                <div class="question-body">
                  <div class="question-data" v-html="Data.QuestionData">
                  </div>
                  <div class="question-body-btn">
                    <ul class="ul-left float-right">
                      <!-- <li class="btn-bag-change" style="display: none;">
                                                <div class="icon-change inline-block"></div>
                                                替换
                                            </li> -->
                      <li class="slide-btn pointer" @click="Fold" :Fold="Data.Id" style="display: block;">展开解析
                        <span class="inline-block arrow-down-2"></span>
                      </li>
                      <!-- <li>
                                                <div class="btn-default btn-question btn-move">
                                                    <div class="icon-move"></div>
                                                    移除</div>
                                            </li> -->
                    </ul>
                  </div>
                  <div class="question-analyze padt-14 mat-10" style="display: none;" :ref="Data.Id">
                    <div class="question-analyze-head">【解析】</div>
                    <div v-html="Data.QuestionAnalyze">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- <div class="paper-404" style="display: none;"><img src="/static/img/nodata_bg.fdf4137.png" alt="">
                        <p>啊哦,当前选项下无套卷可选~</p>
                        <div class="btn-default btn-404">返回选题</div>
                    </div> -->
        </div>
        <!---->
      </div>
      <Spin fix v-if="spinShow">
        <Icon type="load-c" size=18 class="demo-spin-icon-load"></Icon>
        <div>Loading</div>
      </Spin>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import { GetLessonPractice } from "../../services/lesson/preparesClass";

export default {
  name: "PracticeDetails",
  data() {
    return {
      orgID: this.$route.params.orgID, //机构ID
      PracticeDetailsData: [], // 题 数据
      QuestionTypeData: [], // 题型 数据(单选题、填空题等)
      Tittle: this.$route.params.FileName, //练习卷名称
      FileID: this.$route.params.FileID, //练习卷ID
      spinShow: true //load 状态
    };
  },
  components: {},
  methods: {
    /**
     * 获取练习卷详情
     */
    PreviewPractice() {
      this.spinShow = true;
      var params = {
        Id: this.FileID // 练习卷Id !!required!!
      };
      var vm_this = this;
      GetLessonPractice(this.orgID, params)
        .then(function(data) {
          var _Data = data;
          vm_this.PracticeDetailsData = _Data;
          var newData = [];
          for (var i = 0; i < _Data.length; i++) {
            if (
              i == 0 ||
              _Data[i].QuestionTypeId != _Data[i - 1].QuestionTypeId
            ) {
              newData.push({
                QuestionTypeId: _Data[i].QuestionTypeId,
                QuestionType: _Data[i].QuestionType
              });
            }
            _Data[i].QuestionData =
              _Data[0].QuestionData.substr(0, 3) +
              "\u003cspan\u003e" +
              (i + 1) +
              "、\u003c/span\u003e" +
              _Data[i].QuestionData.substr(3);
            _Data[i].href = "#" + _Data[i].Id;
          }
          var num = [
            "一",
            "二",
            "三",
            "四",
            "五",
            "六",
            "七",
            "八",
            "九",
            "十",
            "十一",
            "十二",
            "十三",
            "十四",
            "十五",
            "十六",
            "十七",
            "十八",
            "十九",
            "二十",
            "二十一",
            "二十二",
            "二十三",
            "二十四",
            "二十五",
            "二十六",
            "二十七",
            "二十八",
            "二十九",
            "三十",
            "三十一",
            "三十二",
            "三十三",
            "三十四",
            "三十五",
            "三十六",
            "三十七",
            "三十八",
            "三十九",
            "四十"
          ];
          for (var i = 0; i < newData.length; i++) {
            newData[i].QuestionTypeName =
              num[i] + "." + newData[i].QuestionType;
          }
          vm_this.QuestionTypeData = newData;
          vm_this.spinShow = false;
        })
        .then(function(data) {
          vm_this.$nextTick(() => {
            // 在这里面去获取DOM
            vm_this.ImgUrl();
          });
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    /**
     * 返回上一层
     */
    CallBack() {
      this.$router.back(-1);
    },
    /**
     * 锚点定位功能
     */
    listClick(event) {
      // 用 class="d_jump" 添加锚点
      let _index = event.target.attributes.indexid.value;
      //   console.log(_index);
      let jump = document.querySelectorAll(".d_jump");
      //   console.log(jump);
      // 获取需要滚动的距离
      let total = 51;
      for (let index = 0; index < _index; index++) {
        if (index > 1) {
          total += jump[index - 1].clientHeight + 10;
        }
      }
      //   console.log(total);
      //   // Chrome
      //   document.body.scrollTop = total;
      //   // Firefox
      //   document.documentElement.scrollTop = total;
      //   // Safari
      //   window.pageYOffset = total;

      let distance =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 平滑滚动,时长500ms,每10ms一跳,共50跳
      let step = total / 50;
      if (total > distance) {
        smoothDown();
      } else {
        let newTotal = distance - total;
        step = newTotal / 50;
        smoothUp();
      }
      function smoothDown() {
        if (distance < total) {
          distance += step;
          document.body.scrollTop = distance;
          document.documentElement.scrollTop = distance;
          setTimeout(smoothDown, 10);
        } else {
          document.body.scrollTop = total;
          document.documentElement.scrollTop = total;
        }
      }
      function smoothUp() {
        if (distance > total) {
          distance -= step;
          document.body.scrollTop = distance;
          document.documentElement.scrollTop = distance;
          setTimeout(smoothUp, 10);
        } else {
          document.body.scrollTop = total;
          document.documentElement.scrollTop = total;
        }
      }
    },
    /**
     * 解析展开/收起功能
     */
    Fold(event) {
      if (
        event.target.className == "inline-block arrow-down-2" ||
        event.target.className == "inline-block arrow-up-2"
      ) {
        var text = event.target.parentNode.childNodes[0].data.substr(0, 4);
        // console.log(text);
        if (text == "展开解析") {
          event.target.parentNode.childNodes[0].data = "收起解析";
          event.target.parentNode.childNodes[1].className =
            "inline-block arrow-up-2";
        } else if (text == "收起解析") {
          event.target.parentNode.childNodes[0].data = "展开解析";
          event.target.parentNode.childNodes[1].className =
            "inline-block arrow-down-2";
        }
        // console.log(event);
        var _ref = event.target.parentNode.attributes.Fold.value;
        var _style = this.$refs[_ref][0].attributes[2].value;
        if (_style == "display: block;") {
          this.$refs[_ref][0].attributes[2].value = "display: none;";
        } else if (_style == "display: none;") {
          this.$refs[_ref][0].attributes[2].value = "display: block;";
        }
      } else {
        var text = event.target.childNodes[0].data.substr(0, 4);
        // console.log(text);
        if (text == "展开解析") {
          event.target.childNodes[0].data = "收起解析";
          event.target.childNodes[1].className = "inline-block arrow-up-2";
        } else if (text == "收起解析") {
          event.target.childNodes[0].data = "展开解析";
          event.target.childNodes[1].className = "inline-block arrow-down-2";
        }
        // console.log(event);
        var _ref = event.target.attributes.Fold.value;
        var _style = this.$refs[_ref][0].attributes[2].value;
        if (_style == "display: block;") {
          this.$refs[_ref][0].attributes[2].value = "display: none;";
        } else if (_style == "display: none;") {
          this.$refs[_ref][0].attributes[2].value = "display: block;";
        }
      }
    },
    /**
     * 修改img的src值
     */
    ImgUrl() {
      var imges = document.getElementsByClassName("qs_i");
      for (var i = 0; i < imges.length; i++) {
        for (var j = 0; j < imges[i].attributes.length; j++) {
          if (imges[i].attributes[j].name == "src") {
            imges[i].attributes[j].nodeValue =
              "//s.kaogps.cn/rimages/" + imges[i].attributes[j].nodeValue;
              break
          }
        }
      }
    }
  },
  mounted() {
    this.PreviewPractice();
  }
};
</script>

<style lang="scss" scoped type="text/css">
@import "../sass/main";
input[type="text"] {
  font-size: 14px;
}
#app {
  font-family: "MicrosoftYaHei", "微软雅黑";
  height: 100%;
}
.app-container {
  width: 1200px;
  margin: auto;
  min-height: calc(100% - 80px);
}
html,
body {
  height: 100%;
}
body {
  background-color: #f8f8f8;
  font-size: 16px;
}
.content {
  padding-top: 16px;
  width: 100%;
  position: relative;
}
.content-head {
  width: 100%;
  height: 64px;
  background-color: #fff;
  line-height: 32px;
  text-align: center;
  padding: 16px 24px;
  border-bottom: 1px solid #eee;
}
.content-fixed {
  position: fixed;
  z-index: 8;
  top: 10px;
  width: 1200px;
  .content-head-top {
    width: 100%;
    height: 16px;
    background-color: #f8f8f8;
  }
}
.content-body {
  width: 100%;
  padding: 6px 24px 16px;
  background-color: #fff;
  min-height: 700px;
  padding-bottom: 24px;
}
// 底部
.footer {
  background-color: #f2f2f2;
  font-size: 16px;
  color: #d2d2d2;
  padding: 22px 0 14px 0;
  text-align: center;
  height: 103px;
}

.footer-icon {
  width: 16px;
  margin-left: 47px;
  + .footer-icon {
    margin-left: 26px;
  }
}

.footer-copyright {
  font-size: 12px;
  color: #dcdcdc;
  margin-top: 14px;
}
.btn-bag-change {
  color: #249cf2;
  cursor: pointer;
  .icon-change {
    width: 15px;
    height: 15px;
    background: url("../assets/replaceclass_icn.png") no-repeat;
    background-position-x: -25px;
    background-size: cover;
    vertical-align: middle;
  }
}
.question-body-scroll {
  max-height: 400px;
  overflow: auto;
}
.ul-left li a {
  display: inline-block;
  width: 30px;
  height: 30px;
  color: #333;
}
</style>