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代码没那么完整,大家复制的时候注意。还有就是做的没小米商城那么丝滑,大家可以自行优化以下。

相关推荐
崔庆才丨静觅6 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60616 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅7 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅7 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅7 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment8 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅8 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊8 小时前
jwt介绍
前端
爱敲代码的小鱼8 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax