web app透明渐变的导航栏 | 金金求上进

JerryXia 发表于 , 阅读 (0)

下图为一个简单的实现效果
实现效果

最简实现

html,css准备,一个nav bar,大家都会写的咯^.^

1
2
3
4
<header id="header" style="background-color: rgba(247,247,247,0)" class="transparent_nav">
<img src="img/back.png"/>
<h1>导航栏</h1>
</header>
1
2
3
4
5
6
7
8
.transparent_nav{
position: fixed;
top: 0;
left: 0;
right: 0;
height: 44px;
display: block;
}

接下来就是js部分,将window.scrollY减去一个基线值,如0,再将差与一个固定的offset值比较,如150,得出此时的rgba中的a值

1
2
3
4
5
var header = document.getElementById("header")
window.addEventListener("scroll", function(){
// top-0 offset-150
header.style.backgroundColor = "rgba(247,247,247,"+(window.scrollY-0)/150+")"
});

进阶实现

将透明渐变方法封装一下,使得其可复用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var Transparent = function(element,option){
this.element = element;
this.option = option || {
offset:150,
top:0,
}
this._style = this.element.style
this._bgColor = this._style.backgroundColor
var color = getColor(this._bgColor)
this.R = color[0]
this.G = color[1]
this.B = color[2]
this.handleScroll = function(){
this._style.backgroundColor = "rgba("+this.R+","+this.G+","+this.B+","+(window.scrollY-this.option.top)/this.option.offset+")"
}
window.addEventListener('scroll', this.handleScroll);
}
Transparent(header)

其中,getColor方法的作用是提取rgba的四个参数值,以数组形式返回,可以通过正则匹配,或者最简单的substring,split,想怎么实现这么实现咯!!

就这么简单就完啦,撒花,撒花!!