VUE实现HTML页面滚动,标题实时刷新

follow.gif

源码

<template>
  <div>
    <h1 class="title">current card is {{title}}</h1>
    <div class="section"
         v-for="(item,index )  in list"
         :c-data="item"
         :key="index">
      <p>{{item}}</p>
    </div>
    <div class="footer" style="background:slategray">
      <p>footer</p>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      title: 'hey',
      list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    }
  },
  mounted () {
    let timer = null
    window.addEventListener('scroll', () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {// debounce处理滚动
        let ps = document.getElementsByClassName('section')//获取所有card
        for(let i=0;i<ps.length;i++){
          let e=ps[i]
          let rec = e.getBoundingClientRect()//获取card相对视口的属性
          let h = e.offsetHeight //e的高度,如果为固定值,则可以不用获取,直接写该固定值
          let ch = window.innerHeight / 2 //视口的中间线
          if (ch >= rec.top && ch <= (rec.top + h)) {//当视口的中间线被包含在该card中,改变title为其相关值
            console.log(ch, rec.top, h)
            let cd = e.getAttribute('c-data')
            this.title = cd
            break
          }
        }
      }, 500)

    })
  }
}
</script>
<style lang="less" scoped>
.title {
  position: fixed;
  top: 0;
  background: burlywood;
  width: 100%;
}
.section,.footer{
  height: 250px;
  width: 90%;
  display: flex;
  background: azure;
  box-shadow: 2px 2px 8px 2px black;
  border-radius: 7px;
  margin: 20px auto;
  p {
    margin: auto;
  }
}
</style>

原理

1.监听window scroll事件,利用debounce处理滚动事件
2.获取所有card元素
3.遍历card元素,找出centerline所在的card元素

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容