<!DOCTYPE html> <html> <head> <Meta charset="UTF-8"> <Meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- 在这里用link标签引入中文渐变色 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/chinese-gradient"> <style> /* 清除默认样式 */ * { padding: ; margin: } /* 令html和body全屏显示 */ html, body { height: } /* 上面的那栏 */ .top { /* 设置为固定定位 */ position: fixed; /* 距离上边左边为0 */ top: ; left: ; /* 宽度铺满屏幕 */ width: ; /* 给个合适的高度 */ height: px; /* 令其透明 */ opacity: ; /* 蓝色背景 */ background: var(--靛蓝); } .main { /* 给个合适的高度 */ height: px; /* 渐变背景 */ background: var(--湖蓝); } </style> </head> <body> <div></div> <div></div> <script> // 获取固定栏 const dom = document.getElementsByClassName('top')[] window.addEventListener('scroll', _ => { // 获取偏移值 const top = document.documentElement.scrollTop // 设置一个合适的范围 if (top <= ) { // 对opacity作计算,透明度从起始到1随偏移值而改变 const opacity = top / // 令上栏的透明度变成计算后的透明度 dom.style.opacity = opacity } else { // 在移动一定范围后令其完全不透明 dom.style.opacity = } }) </script> </body> </html>
怎么样,是不是很炫酷呢?不过可惜无法用 CSS 来判断屏幕滑动了多少距离,所以渐隐渐现的 效果 用到了一点点的 JS。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did100590