<body>
<div id="nav"></div>
<script>
var nav = document.getElementById("nav");
// 1.对窗口执行监听事件
window.onscroll = function(){
// 2.获取滚动条的高度
var scrollTop = document.documentElement.scrollTop;
// 3.得到透明度
var opacity = scrollTop/200;
// opacity 透明度不能大于1
if(opacity>1){
opacity=1
}
nav.style.opacity = opacity;
console.log(opacity)
}
</script>
方法2
<style>
*{margin: 0;padding: 0;}
div{
height: 50px;
width: 100%;
background-color: red;
position: fixed;
opacity: 0;
}
body{
height: 2000px;
}
</style>
</head>
<body>
<div id="app"></div>
<script>
var app = document.getElementById("app");
onscroll = function(){
var scrollTop = document.documentElement.scrollTop;
var opacity = scrollTop/200;
if(opacity>1){
opacity=1;
}
app.style.opacity=opacity;
}
</script>