有个需求:导航条是默认背景色, 页面向上滑动后,导航条变为有颜色的背景
思路:
js判断滚动条滑动到200像素后
动态给元素设置一个属性data-fixed,
给属性设置个css样式
html
<div class="main-header" id="main_header">
<div class="menu">
<div class="nav">
<img src="/static/images/logo.png" class="nav-item logo-img">
<a class="nav-item" href="#">首页</a>
<a class="nav-item" href="#">展厅</a>
<a class="nav-item" href="#">资讯</a>
<a class="nav-item" href="#">加盟</a>
</div>
</div>
</div>
css
.main-header{
background-color: rgba(0,0,0,0.1);
background-image: none;
}
.main-header[data-fixed='fixed']{
position: fixed;top:0;left: 0;right: 0;z-index: 3;
background-image: linear-gradient(-225deg, #231557 0%, #44107A 29%, #FF1361 67%, #FFF800 100%);
}
js
<script>
//本文来自csdn博客, 禁止采集
function ceiling(obj){
var ot = 200;
document.onscroll = function(){
var st=document.body.scrollTop || document.documentElement.scrollTop;
obj.setAttribute("data-fixed",st >= ot ? "fixed":'');
}
}
window.onload=function () {
var wrap = document.getElementById('main_header');
ceiling(wrap);
}
</script>