js+vue,前端关于页面滚动让头部菜单淡入淡出实现原理

今天遇到个需求:我这里借用小米商城的详情页做个比喻吧。

刚开始其商品详情页是这样的:

当滚动到一定高度时,是这样的:

可以看到当滚动到轮播图底下的时候,详情页的菜单完全显现出来。

以下上代码:

HTML:

html 复制代码
<div class="detail-header">
			<div class="left operate" :style="{'background-color':iconStyle.BackgroundColor,'color':iconStyle.color}">
				<span class="iconfont icon-fanhui"></span>
			</div>
			<div class="active-box" :style="{'opacity':Opacity}">
				<div>商品</div>
				<div>评价</div>
                <div>评价</div>
                <div>详情</div>
                <div>推荐</div>
			</div>
			<div class="right operate" :style="{'background-color':iconStyle.BackgroundColor,'color':iconStyle.color}">
				<span class="iconfont icon-home"></span>
			</div>
			<div class="header-bg" :style="{'opacity':Opacity}"></div>
		</div>

css:

css 复制代码
.detail-header{
			position: absolute;
			left: 0;
			right: 0;
			height: 1.173333rem;
			z-index: 999;
			.active-box{
				position: absolute;
				left: 50%;
				transform: translateX(-50%);
				white-space: nowrap;
				display: flex;
				align-items: center;
				justify-content: center;
				line-height: 1.173333rem;
				font-size: 0.426667rem;
				opacity:0;
				z-index:67;
				>div{
					padding: 0 0.4rem;
				}
			}
			.operate{
				position: absolute;
				width: 0.906667rem;
				height: 0.906667rem;
				line-height: 0.906667rem;
				border-radius: 50%;
				background-color: rgba(0,0,0,.3);
				color: #fff;
				text-align: center;
				margin: 0.133333rem;
				display: table;
				z-index: 58;
				.iconfont{
					display: table-cell;
					font-size: 0.4rem;
					vertical-align: middle;
				}
			}
			.left{
				left:0;
			}
			.right{
				right: 0;
			}
			.header-bg{
				background-color: #fff;
				height: 100%;
				opacity: 0;
				z-index: 66;
			}
		}

js:

javascript 复制代码
data(){
			return{
				Opacity:0,
				iconStyle:{
					BackgroundColor:'rgba(0, 0, 0, 0.3)',
					color:'#fff'
				}
			}
		},
ContentScroll(e){
				let top = (e.target.scrollTop / 120);
				this.Opacity = top >= 1?1:top;
				console.log(top)
				if(top >= 1){
					this.iconStyle.BackgroundColor = 'unset'
					this.iconStyle.color = '#333'
				}else{
					this.iconStyle.BackgroundColor = 'rgba(0, 0, 0, 0.3)'
					this.iconStyle.color = '#fff'
				}
			}

在上面代码中可以看出,头部代码是绝对定位的,头部不要设置背景图,因为我么是通过设置opacity来控制元素的显示隐藏的,所以我们用元素来代替背景的作用。只要设置好图层z-index就不会发生:操作菜单和按钮被遮挡的情况。记住要设置定位哦!

这里的e.target.scrollTop / 120 ;120是你轮播图的高度,根据自己的情况而定。

注意:这里主要是记录实现原理,js代码没那么完整,大家复制的时候注意。还有就是做的没小米商城那么丝滑,大家可以自行优化以下。

相关推荐
神奇的程序员18 小时前
我的软件冲进苹果商店下载榜前 50 了
前端
阳光是sunny18 小时前
别再被 worktree 绕晕了!AI 编程时代你必须掌握的 Git 隔离神器
前端·人工智能·后端
万少19 小时前
万少的博客 - 技术分享与解决方案
前端·javascript·后端
尘世中一位迷途小书童1 天前
用 Cesium 撸了一个森林火情监控大屏,弧线、粒子、发光效果都齐了
前端·javascript
IT_陈寒1 天前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
月光下的丝瓜1 天前
Flutter 国内安装指南
前端·flutter
玄星啊1 天前
AI 编程的第 30 天,我怀念古法 Coding 了
前端·ai编程
Jolyne_1 天前
Angular基础速通
前端·angular.js
锋行天下1 天前
半秒开!还有谁!!!
前端·vue.js·架构
代码搬运媛1 天前
git 下中文文件名乱码问题解决
前端