一、需求分析
当用户向上滚动屏幕后,我们希望上方的图片可以有渐变的模糊效果
也就是说 我们需要:
1、监听页面的滚动
2、计算模糊度关于滚动距离的函数
3、设置DOM元素的高斯模糊
二、关于backdrop-filter
这个CSS属性的作用是:对元素后面的所有内容应用过滤效果
<template>
<div class="bg-image" ref="bgImage">
<div class="filter" ref="filter"></div>
</div>
</template>
注意:元素本身或其背景需要设置一定的透明度
<style scoped lang="stylus">
.filter
background: rgba(7, 17, 27, 0.4)
</style>
关于backdrop-filter属性的更多取值可以参考MDN官方文档
三、具体实现过程
当用户开始滚动屏幕时,会触发scroll事件
通过已经封装好的better-scroll组件,传入参数pos
将pos.y赋值给this.scrollY
methods: {
scroll(pos) {
this.scrollY = pos.y
}
}
通过watch监听scrollY的变化
初始化变量 blur=0
设置变量percent 为 scroolY与图片绝对高度(ImageHeight)的比值
使得blur从0开始,随着|scrollY|变大而变大,直到20px
watch:{
scrollY(newY) {
let blur = 0
const percent = Math.abs(newY/ this.ImageHeight)
if (newY<=0) {
blur = Math.min(20 * percent, 20)
}
this.$refs.filter.style['backdrop-filter'] = `blur(${blur}px)`
this.$refs.filter.style['webkitBackdrop-filter'] = `blur(${blur}px)`
}
}
最终效果如下: