如何创建:响应式顶部导航栏
- Vorherige Seite Top-Navigation
- Nächste Seite Navigation aufteilen
学习如何使用 CSS 和 JavaScript 创建响应式顶部导航栏。
响应式顶部导航菜单
请调整浏览器窗口大小,查看响应式导航菜单的工作方式:
创建响应式顶部导航菜单
第一步 - 添加 HTML:
<!-- 加载图标库以在小屏幕上显示汉堡菜单(横杠) --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="topnav" id="myTopnav"> <a href="#home" class="active">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <a href="#about">About</a> <a href="javascript:void(0);" class="icon" onclick="myFunction()"> <i class="fa fa-bars"></i> </a> </div>
class="icon" 的链接用于在小屏幕上打开和关闭顶部导航。
第二步 - 添加 CSS:
/* 为顶部导航添加黑色背景色 */ .topnav { background-color: #333; overflow: hidden; } /* 设置导航栏中链接的样式 */ .topnav a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } /* Ändern Sie die Farbe des Links bei der Mausüberlagerung */ .topnav a:hover { background-color: #ddd; color: black; } /* Fügen Sie eine Aktionsklasse hinzu, um die aktuelle Seite hervorzuheben */ .topnav a.active { background-color: #04AA6D; color: white; } /* Verstecke den Link, um die obere Navigation auf kleinen Bildschirmen zu öffnen und zu schließen. */ .topnav .icon { display: none; }
Fügen Sie eine Medienabfrage hinzu:
/* Bei einer Bildschirmbreite von weniger als 600 Pixeln werden alle Links außer dem ersten ("Home") versteckt. Zeige Links, um die obere Navigation (.icon) zu öffnen und zu schließen. */ @media screen and (max-width: 600px) { .topnav a:not(:first-child) {display: none;} .topnav a.icon { float: right; display: block; } } /* Wenn der Benutzer auf das Symbol klickt, fügt JavaScript der topnav die Klasse "responsive" hinzu. Diese Klasse macht topnav auf kleinen Bildschirmen besser aussehend (verkehrt die Anordnung der Links von horizontal zu vertikal). */ @media screen and (max-width: 600px) { .topnav.responsive {position: relative;} .topnav.responsive a.icon { position: absolute; right: 0; top: 0; } .topnav.responsive a { float: none; display: block; text-align: left; } }
Dritter Schritt - Fügen Sie JavaScript hinzu:
/* Wenn der Benutzer auf das Symbol klickt, wird die Klasse "responsive" in topnav hinzugefügt oder entfernt */ function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; } else { x.className = "topnav"; } }
Verwandte Seiten
Tutorial:CSS-Navigationsleiste
- Vorherige Seite Top-Navigation
- Nächste Seite Navigation aufteilen