pc端制作一个顶部固定的菜单栏

发布于:2024-07-01 ⋅ 阅读:(19) ⋅ 点赞:(0)

效果

在这里插入图片描述

hsl颜色

hsl颜色在css中比较方便 https://www.w3school.com.cn/css/css_colors_hsl.asp

  • 色相(hue)是色轮上从 0 到 360 的度数。0 是红色,120 是绿色,240 是蓝色。
  • 饱和度(saturation)是一个百分比值,0% 表示灰色阴影,而 100% 是全色。
  • 亮度(lightness)也是百分比,0% 是黑色,50% 是既不明也不暗,100%是白色。
    在base.css中,定义基本的颜色变量及其它变量
:root{
    --header-height: 3.5rem;
    --body-color: hsl(230, 100%, 96%);
    --z-fixed: 100;
}

渐变

transition,定义一个元素在不同状态之间切换的时候定义不同的过渡效果,多个属性用逗号隔开

布局

header中定义固定定位

.header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: var(--body-color);
    z-index: var(--z-fixed);
    transition: box-shadow .4s, background-color .4s;
}

定义滚动后,菜单的颜色和阴影。

.shadow-header{
  box-shadow: 0 2px 16px hsla(0, 0%, 0%, .1);
}

内容部分,定义上下边距

.section {
    padding-block: 5rem 1rem;
}

js

滚动菜单,通过js实现
js选取要操作的对象 https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementsByClassName

const shadowHeader = () =>{
    const header = document.getElementById('header')
    this.scrollY >= 50 ? header.classList.add('shadow-header') 
                       : header.classList.remove('shadow-header')
}
window.addEventListener('scroll', shadowHeader)

完整代码

以下代码是完整的

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <header class="header">
        <nav class="nav">
            <a href="" class="title">2024年第13次安全月活动</a>
            <div>
                <a href="" class="nav_button">登录</a>
            </div>
        </nav>
    </header>
    <main>
        <section id="home">
            <p>示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字示例文字</p>
        </section>
    </main>
<style>
.header{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: hsl(230, 100%, 96%);
  z-index: 100;
  transition: box-shadow .4s,background-color .4s;
}
.nav{
    max-width: 1200px;
    margin-inline: auto;
  height: 3.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
#home{
    padding-block:5rem 1rem;
    max-width: 1200px;
    margin-inline: auto;
    height: 2000px;
    background-color: aquamarine;
}
.shadow-header{
  box-shadow: 0 2px 16px hsla(0, 0%, 0%, .1);
}
</style>
<script>
    const shadowHeader = () =>{
    const header = document.getElementsByClassName('header')[0]
    console.log("header::",header)
    this.scrollY >= 50 ? header.classList.add('shadow-header') 
                       : header.classList.remove('shadow-header')
}
window.addEventListener('scroll', shadowHeader)
</script>
</body>
</html>

网站公告

今日签到

点亮在社区的每一天
去签到