VUE笔记:视差滚动(Parallax Scrolling)的实现方法
在对曲靖M官方进行改版原型设计时,考虑采用视差滚动让用户使用体验更加印象深刻。今日曲靖官网首页正式发布,页顺便把VUE视差滚动的实现方法给记录一下。
视差滚动
视差滚动(Parallax Scrolling)指网页滚动过程中,多层次的元素进行不同程度的移动。
原理
传统的网页的文字、图片、背景都是一起按照相同方向相同速度滚动的,而视差滚动则是在滚动的时候,内容和多层次的背景实现或不同速度,或不同方向的运动。有的时候也可以加上一些透明度、大小的动画来优化显示。
示例
简单实现
<template>
<div class="main-container">
<div class="content-item first-container">内容1</div>
<div class="activebg fisrtbg" id="pic1" v-bind:style="{'background-position-x':positionX,'background-position-y': positionY1+'px' }"></div>
<div class="content-item second-container">内容2</div>
<div class="activebg secondbg" id="pic2" v-bind:style="{'background-position-x':positionX,'background-position-y': positionY2+'px' }"></div>
<div class="content-item third-container">内容3</div>
<div class="activebg thirdbg" id="pic3" v-bind:style="{'background-position-x':positionX,'background-position-y': positionY3+'px' }"></div>
<div class="content-item fourth-container">内容4</div>
</div>
</template>
<script>
export default {
name: 'Main',
data() {
return {
ratio: 0.05,
positionX: "50%",
positionY1: 30,
positionY2: 100,
positionY3: 150,
Y1: 0,
Y2: 0,
Y3: 0
}
},
mounted() {
window.addEventListener("scroll", this.handleScroll)
window.onload = () => {
let pic1 = document.getElementById("pic1")
let pic2 = document.getElementById("pic2")
let pic3 = document.getElementById("pic3")
this.positionY1 = this.Y1 = pic1.offsetTop * this.ratio
this.positionY2 = this.Y2 = pic2.offsetTop * this.ratio
this.positionY3 = this.Y3 = pic3.offsetTop * this.ratio
}
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll)
},
methods: {
handleScroll() {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
this.positionY1 = this.Y1 - scrollTop * this.ratio //原始高度-滚动距离*视差系数
this.positionY2 = this.Y2 - scrollTop * this.ratio
this.positionY3 = this.Y3 - scrollTop * this.ratio
if (scrollTop > 900) {
this.showFixHeader = false
this.showHeaderNav = true
} else {
this.showFixHeader = true
this.showHeaderNav = false
}
}
}
}
</script>
<style lang="scss" scoped>
.main-container {
min-width: 1066px;
.content-item {
background-color: #fff;
width: 100%;
&.first-container {
min-height: 50vh;
}
&.second-container {
min-height: 50vh;
}
&.third-container {
min-height: 50vh;
}
}
&.fourth-container {
min-height: 50vh;
}
}
.activebg {
position: relative;
width: 100%;
height: 600px;
background: #fff;
background-attachment: fixed;
background-position: center 0;
background-repeat: no-repeat;
&.fisrtbg {
background-image: url(../../assets/home/3.jpg);
}
&.secondbg {
background-image: url(../../assets/home/1.png);
}
&.thirdbg {
background-image: url(../../assets/home/4.jpg);
}
}
}
</style>
回复
要发表评论,您必须先登录。