响应式导航栏
本课属于 Coddy HTML 学习旅程的“JavaScript 实战”单元。第 26 课,共 27 课。
挑战
简单我们已经为介绍玛雅文明的网站编写了汉堡菜单和导航栏的 HTML 和 CSS。
你的任务是让 JavaScript 正常运行,这样点击按钮时,菜单就会打开和关闭。
按照以下步骤操作:
- 创建一个变量,用来存储汉堡菜单按钮元素,使用
getElementById("burger")。 - 再创建一个变量,用来存储导航菜单,使用
getElementById("navMenu")。 - 为按钮添加事件监听器,让它在被点击时运行一个函数。
- 在这个函数中:
- 切换按钮上的
"active"类(这会让 3 条线动起来)。 - 切换菜单上的
"active"类(这会显示或隐藏链接)。
- 切换按钮上的
正确完成后,点击汉堡菜单按钮时,3 条线会变成“X”,导航菜单也会显示出来。
亲手试试
<!DOCTYPE html>
<html>
<head>
<title>Maya Civilization</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<div class="logo">Maya World</div>
<div id="burger" class="burger-btn">
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
</div>
<nav id="navMenu" class="nav-links">
<a href="#">Home</a>
<a href="#">History</a>
<a href="#">Culture</a>
<a href="#">Architecture</a>
</nav>
</header>
<main>
<section class="hero">
<h1>The Maya Civilization</h1>
<p>
The Maya civilization thrived in Mesoamerica, known for its remarkable
achievements in astronomy, mathematics, and monumental architecture.
</p>
</section>
<section class="content">
<h2>Legacy of the Maya</h2>
<p>
The Maya left behind impressive cities, pyramids, and written language.
Their deep knowledge of astronomy influenced calendars and rituals, while
their art and traditions continue to inspire today.
</p>
<img src="https://upload.wikimedia.org/wikipedia/commons/e/ea/El_Castillo%2C_Chich%C3%A9n_Itz%C3%A1.jpg"
alt="Maya Pyramid" class="content-img">
</section>
</main>
<script src="script.js"></script>
</body>
</html>
JavaScript 实战中的所有课
自己练习: Web 在线编辑器