固定定位+渐隐渐现
相信大家日常用手机的时候会见过这种:
<!DOCTYPE html>
<html lang="en">
<head>
< charset="UTF-8">
< 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 class="top"></div>
<div class="main"></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。