js 实现导航栏滑动透明渐变样式

来源:blog.csdn.net 更新时间:2023-05-25 21:55


<!DOCTYPE html>
<html>
<head>    
    <meta charset="utf-8">    
    <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />    
    <title>js 实现导航栏滑动渐变样式</title>    
    <style type="text/css">    
        *{
            padding: 0;
            margin: 0;
        }
        img{
            data-width: 100%;
        }     
        header {            
            position: fixed;            
            left: 0;            
            top: 0;            
            right: 0;            
            z-index: 50;            
            data-height: 40px;            
            text-align: center;            
            background: rgba(255,255,255,0);        
            color: rgba(66,66,66,0);            
            font-size:20px;            
            line-data-height: 40px;
        }    
    </style>
</head>
<body>    
    <header id="header">首页</header>
    <img src="http://xxiaoyuan.top/static/img/banner/banner1.jpg"/>
    <img src="http://xxiaoyuan.top/static/img/banner/banner1.jpg"/>
    <img src="http://xxiaoyuan.top/static/img/banner/banner1.jpg"/>
    <img src="http://xxiaoyuan.top/static/img/banner/banner1.jpg"/>
    <img src="http://xxiaoyuan.top/static/img/banner/banner1.jpg"/>
    <img src="http://xxiaoyuan.top/static/img/banner/banner1.jpg"/>
    <img src="http://xxiaoyuan.top/static/img/banner/banner1.jpg"/>
    <img src="http://xxiaoyuan.top/static/img/banner/banner1.jpg"/>
    <img src="http://xxiaoyuan.top/static/img/banner/banner1.jpg"/>
</body>
<script>        
    window.onscroll=function(){
        var h =document.documentElement.scrollTop||document.body.scrollTop;
        console.log(h*2.5);      //控制台查看监听滚动  
        var headerTop =document.getElementById("header");            
        if( h >=40) {       //header的高度是40px;     
            headerTop.style.background="#fff";            
            headerTop.style.color="rgba(66,65,66,1)";            
        }else{    
            if(h<10){
                //40*2.5=100;这样透明度就可以由0渐变到100%;
                headerTop.style.background="rgba(255,255,255,0.0"+h*2.5+")";  
                headerTop.style.color="rgba(66,66,66,0.0"+h*2.5+")";            
            }else if(h>10 && h<= 40){
                headerTop.style.background="rgba(255,255,255,0."+h*2.5+")"; 
                headerTop.style.color="rgba(66,66,66,0."+h*2.5+")";            
 
            }            
 
        }        
    };
</script>
</html>