Я новичок в html / css и следую этому руководству, чтобы создать адаптивный заголовок с выпадающим меню: https://www.w3schools.com/howto/howto_js_responsive_navbar_dropdown.asp
Я хочу знать, возможно ли изменить положение ссылок, как встатья, когда область просмотра мала, если ссылки разделены внутри разных div, один div содержит домашнюю ссылку, а другой div содержит остальные ссылки плюс выпадающий div и его содержимое.
Итак, я попытался сделать это и наполовину работал, когда маленькие ссылки исчезнут и появится значок меню гамбургера.Проблема в том, что при маленьком щелчке по значку ссылки не отображаются под навигацией или домашней ссылкой, как в статье.Две ссылки все еще отображаются рядом с «Домой» и недоступны, выпадающий список выглядит нормально, а последняя ссылка также выглядит нормально.Я не уверен, как правильно это стилизовать.
Я понимаю, что с помощью фреймворка было бы намного проще, но, поскольку я новичок, я подумал, может быть, мне следует попробовать это только с html / css / javascript.
Любая помощь или направление приветствуются, спасибо!
Пример того, что я хочу сделать, используя div, когда область просмотра мала, если это возможно: Ссылка на то, что я хочу, потому что я могу 'пока не отправляю фотографии
Что происходит вместо
Ниже приведен код, который у меня есть.Изменения, которые я сделал из оригинала, заключают в себе домашнюю ссылку и другие ссылки в отдельные элементы div и некоторые позиции, которые я оставил как фиксированные, потому что я хотел, чтобы панель навигации двигалась с прокруткой.Я также изменил метод выпадающего меню на щелчок, потому что я не думаю, что у мобильных телефонов есть способ зависания.
Если это помогает, я думаю, что проблема заключается в CSS, где я добавляю стили для «отзывчивого»учебный класс.
function responsiveLinks() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function clickDropdown() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
body, html {
height:100%;
}
body {
background-color: black;
color:white;
font-family: Helvetica;
text-transform:none;
margin: 0 auto;
padding-top: 32px;
}
.topnav {
position: fixed; /* Set the navbar to fixed position to scroll */
top: 0; /* Position the navbar at the top of the page */
width: 100%; /* Full width */
background-color: #333;
z-index:1;
}
.topnav a {
color: white;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
float: left;
}
/* Hide the link that should open and close the topnav on small screens */
.topnav .icon {
display: none;
}
/* Dropdown container - needed to position the dropdown content */
.dropdown {
float:left;
position:relative;
}
/*Style the dropdown button */
.dropdown .dropbtn {
font-size: 17px;
border: none;
outline: none;
color: white;
background-color: inherit;
font-family: inherit;
margin: 0;
padding: 14px 16px;
cursor: pointer;
}
/* Style the dropdown content (hidden by default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
/* Style the links inside the dropdown */
.dropdown-content a {
float: none;
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}
/* Add a background on topnav links and the dropdown button on hover */
.topnav a:hover, .dropdown:hover .dropbtn {
background-color: #555;
color: white;
}
/* Add a grey background to dropdown links on hover */
.dropdown-content a:hover {
background-color: #ddd;
color: black;
}
.show {display:block;} /* For use with clickDropdow() */
/* When the screen is less than 600 pixels wide, hide the links div and its contents. Show the link that contains should open and close the topnav (.icon) */
@media screen and (max-width: 600px) {
.topnav .links {
display: none; /*Changed to work with the divs, hides the whole links div*/
}
.topnav a.icon {
background: inherit;
float:right;
display: block;
position: fixed;
right: 0;
top: 0;
padding: 10px;
}
}
/* The "responsive" class is added to the topnav with JavaScript when the user clicks on the icon. This class makes the topnav look good on small screens (display the links vertically instead of horizontally) */
@media screen and (max-width: 600px) {
.topnav.responsive {
position: fixed;
}
.topnav.responsive a.icon {
position: fixed;
right: 0;
top: 0;
}
.topnav.responsive .links{
background:grey;
float: none;
display: block;
text-align: left;
}
.topnav.responsive .dropdown {
float: none;
}
.topnav.responsive .dropdown-content {
position: relative;
}
.topnav.responsive .dropdown .dropbtn {
display: in-line;
width: 100%;
text-align: left;
}
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" type="text/css" href="./style.css"/>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<title>Page</title>
</head>
<body>
<div class="topnav" id="myTopnav">
<div id="logo">
<a href="home.html"><img src="" width="50" height="50" alt="Home"/></a>
</div> <!-- end logo -->
<div class="links">
<a href="#news">News</a>
<a href="#contact">Contact</a>
<div class="dropdown">
<button onclick="clickDropdown()" class="dropbtn">Dropdown
<i class="fa fa-caret-down"></i>
</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div><!-- end dropdown contents -->
</div><!-- end dropdown -->
<a href="#about">About</a>
</div><!-- end links -->
<a href="javascript:void(0);" class="icon" onclick="responsiveLinks()">☰</a>
</div> <!-- end topnap -->
</body>
</html>