固定定位+渐隐渐现
1. 前言
这样的话不但会在刚进入页面时显得更加的整洁,而且更是丰富了交互的趣味性。
2. 实现
<!DOCTYPE html>
<html lang="en">
<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 {
/* 给个合适的下边距 */
margin-bottom: px;
/* 给个合适的高度 */
height: px;
/* 渐变背景 */
background: var(--天蓝)
}
/* 下面的那栏 */
.bottom {
/* 设置为固定定位 */
position: fixed;
/* 距离下边左边为0 */
bottom: ;
left: ;
/* 宽度铺满屏幕 */
width: ;
/* 给个合适的高度 */
height: px;
/* 蓝色背景 */
background: var(--靛蓝)
}
</style>
</head>
<body>
<div class="top"></div>
<div class="main"></div>
<div class="bottom"></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>
运行结果:
通过我们对移动端的各种网站的观察发现,通常来说下面那栏是不会渐隐渐现的,所以这里下栏一直是固定的。
3. 结语
不过下一章可就和这一章不那么相似了,因为下一章是每天刷微博逛朋友圈所经常看到的:九! 宫! 格!