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

follow.gif

源码

current card is {{title}}

v-for="(item,index ) in list"

:c-data="item"

:key="index">

{{item}}

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

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)

})

}

}

.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;

}

}

原理

1.监听window scroll事件,利用debounce处理滚动事件

2.获取所有card元素

3.遍历card元素,找出centerline所在的card元素

你可能感兴趣的:(html页面自动刷新滚动)