效果图:

Animation1.gif
效果描述:
两个背景颜色:透明色,黑色
两个定位状态:flexed(吸顶效果) (黑色); 绝对定位 (透明色)
根据页面滑动来改变状态,
滑动为0时:透明色,置于页面顶端。此时是绝对定位。
开始向下滑动:绝对定位 => flexed(吸顶效果)
继续向下滑动(略大于导航栏高度时,隐藏导航栏(收缩效果)): flexed定位 => 绝对定位
向上滑动时:绝对定位 => flexed(吸顶效果)
导航布局/样式:
<div class="nav" id="nav1">
<div class="nav-inner">
<el-menu
class="el-menu-demo"
mode="horizontal"
:background-color="bgcstatus ? '#2d2e30' : 'rgba(242, 244, 248, 0)'"
text-color="#f5f6f7"
active-text-color="#ffd04b"
:router="true"
>
<el-menu-item index="/home"><i class="el-icon-s-home"></i>首页</el-menu-item>
<el-menu-item index="/modules"><i class="el-icon-menu"></i>组件</el-menu-item>
<el-menu-item index="/aboutme"><i class="el-icon-s-custom"></i>关于作者</elmenu-item>
</el-menu>
</div>
</div>
<style>
.nav {
display: flex;
position: absolute;
z-index: 1;
width: 100%;
height: 60px;
background-color: rgba(242, 244, 248, 0);
}
.nav-active {
position: fixed;
display: flex;
z-index: 9999;
width: 100%;
height: 60px;
background-color: #2d2e30;
}
</style>
实现效果:
/* 导航栏 */
var nav = document.getElementById("nav1"); //导航栏
var scrollTop = 0,
topValue = getScrollTop();
document.onscroll = function(e) {
var btop = document.documentElement.scrollTop || document.body.scrollTop;
if (btop == 0) {
nav.className = "nav";
this.bgcstatus = false; // 判断element-menu的背景颜色
} else {
scrollTop = getScrollTop();
if (scrollTop <= topValue) {
// 上滑
nav.className = "nav-active";
this.bgcstatus = true;
startmove(0); // 导航出现效果
} else {
// 下滑
if (btop < 200) {
nav.className = "nav-active";
this.bgcstatus = true;
} else if (btop > 200) {
startmove(-60); // 导航收缩效果
} else {
nav.className = "nav"; // 等同于消失
}
}
setTimeout(function() {
topValue = scrollTop;
}, 0);
}
};
function getScrollTop() {
var scrollTop = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
} else if (document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
}
// 收缩效果
var timer;
function startmove(target) {
clearInterval(timer); //清除定时器,以免多次触发定时器导致速度越来越快而不是匀速前进
timer = setInterval(function() {
var speed = 0;
if (nav.offsetTop > target) {
speed = -10;
} else {
speed = 10;
}
if (nav.offsetTop == target) {
clearInterval(timer);
} else {
nav.style.top = nav.offsetTop + speed + "px";
}
}, 20);
}
/* 导航栏 */
知识小结:
1、offsetWidth: 为元素的width+元素的padding+边框的宽度
2、offsetLeft、offsetTop、offsetRight、offsetBottom
以offsetLeft为例进行说明,在不同的浏览器中其值不同,且与父元素的position属性(relative,absolute,fixed)有关。
2.1在父元素均不设置position属性时,在Chrome,opera和IE浏览器中offsetLeft是元素边框外侧到浏览器窗口内侧的距离且body.offsetLeft=0,
2.2当父元素设置position元素时又分为两种情况,
2.2.1如果父元素时body且body设置了position属性,在Chrome和opera浏览器中offsetLeft是元素边框外侧到body边框外侧的距离,
2.2.2如果父元素不是body元素且设置了position属性时,offsetLeft为元素边框外侧到父元素边框内侧的距离(各浏览器情况一致)。
3.document.onscroll
onscroll 事件在元素滚动条在滚动时触发。