Я новый пользователь и новый программист, просто пытаюсь создать сайт-портфолио. Я хотел, чтобы на моем сайте были вкладки, которые могли бы переключаться между контентом, но я вообще не могу заставить работать JavaScript.
Я просто использовал шаблон из w3schools и заменил его именами классов/идентификаторов в своем коде. Я ожидал нормальной обычной функции вкладок. Здесь происходит следующее: отображается все содержимое двух вкладок, и когда вы щелкаете любую из вкладок, оно исчезает, пока вы не обновите страницу.
Прошу прощения, что код не минимален, я даже не знаю, насколько его можно обрезать, не теряя контекста. Если это имеет значение, я запустил этот код в Firefox
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
@font-face {
font-family: "Roboto" src: url("Roboto-Bold-webfont.woff") format("woff");
font-style: normal;
font-weight: 700;
}
@font-face {
font-family: "Roboto" src: url("Roboto-Regular-webfont.woff") format("woff");
font-style: normal;
font-weight: 400;
}
body {
width: 100%;
font-family: "Roboto", sans-serif;
font-size: 15px;
line-height: 1.5em;
}
.page {
display: flex;
justify-content: space-around;
margin-top: 50px;
}
.sidebar {
display: flex;
justify-content: flex-start;
flex-direction: column;
align-items: center;
position: fixed;
top: 100px;
left: 50px;
width: 400px;
/* border: 1px solid red; */
}
.sidebar-button {
display: flex;
align-items: center;
justify-content: center;
width: 400px;
}
.sidebar img {
height: 200px;
}
.content {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin: 50px 0 0 400px;
/* border: 1px solid red; */
}
.page-tab {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.tab {
display: flex;
justify-content: center;
align-items: center;
width: 300px;
}
.sidebar-button,
.tab {
margin: 10px;
height: 45px;
background-color: #D99023;
border-radius: 5px;
border: none;
cursor: pointer;
color: #FFFFFF;
font-family: "Roboto", sans-serif;
font-weight: 700;
font-size: 20px;
}
.sidebar-button:hover,
.tab:hover {
background-color: #9C5400;
}
.sidebar-button a {
text-decoration: none;
color: #FFFFFF;
}
.page-tab button:active {
background-color: #9C5400;
color: #FFFFFF;
}
.gallery-container {
display: flex;
justify-content: center;
flex-wrap: wrap;
padding-top: 50px;
}
.gallery-container img {
height: 350px;
}
<!DOCTYPE html>
<html lang = "en" dir = "ltr">
<head>
<meta charset = "utf-8">
<title>Frogcroaks</title>
<link rel = "stylesheet" href = "master.css">
</head>
<body>
<div class = "page">
<nav class = "sidebar">
<img src = "images/logo.png" alt = "">
<button class = "sidebar-button">
<a href = "home.html">Home</a>
</button>
<button class = "sidebar-button">
<a href = "commissions.html">Commission</a>
</button>
<button class = "sidebar-button">
<a href = "about.html">About & Contact</a>
</button>
</nav>
<div class = "content">
<nav class = "page-tab">
<button class = "tab" onclick = "openGallery(event, 'character-design')">
Character Design
</button>
<button class = "tab" onclick = "openGallery(event, 'illustration')">
Illustration
</button>
</nav>
<div id = "character-design" class = "gallery-container gallery">
<img src = "images/poufdesign1.png" alt = "" class = "gallery">
<img src = "images/poufdesign2.png" alt = "" class = "gallery">
<img src = "images/poufdesign3.png" alt = "" class = "gallery">
<img src = "images/fairy-ring.png" alt = "" class = "gallery">
<img src = "images/luminae.png" alt = "" class = "gallery">
<img src = "images/griffoy.png" alt = "" class = "gallery">
<img src = "images/pokemon.png" alt = "" class = "gallery">
</div>
<div id = "illustration" class = "gallery-container gallery" style = "display = " none "">
<img src = "images/eloa-growth2.png" alt = "" class = "gallery">
<img src = "images/eloa-growth1.png" alt = "" class = "gallery">
<img src = "images/seviper-zangoose.png" alt = "" class = "gallery">
</div>
</div>
</div>
<script>
function openGallery(evt, galleryName) {
// Declare all variables
var i, gallery, tab;
gallery = document.getElementsByClassName("gallery");
for (i = 0; i < gallery.length; i++) {
gallery[i].style.display = "none";
}
tab = document.getElementsByClassName("tab");
for (i = 0; i < tab.length; i++) {
tab[i].className = tab[i].className.replace(" active", "");
}
document.getElementById(galleryName).style.display = "block";
evt.currentTarget.className += " active";
}
</script>
</body>
</html>
@JaromandaX эта часть была скопирована прямо из примера шаблона, поэтому я не уверен, как бы я ее изменил.
тогда шаблон примера w3schools неверен (поднимите руки, если вы удивлены, что w3schools неправ) или вы что-то изменили... например, я сомневаюсь, что какой-либо даже мало-мальски полезный сайт предложит это style = "display = " none ""
, поскольку это чистый мусор
вкладки с Javascript не требуется
В предоставленном вами коде много ошибок. Вот рабочее решение. Я написал JavaScript в отдельный файл (script.js) и связал его с HTML с помощью тега с атрибутом src
. Если вы предпочитаете писать это в документе HTML так же, как в своем коде, замените содержимое тега <script>
вашего HTML кодом JS, написанным ниже.
"use strict";
const tabBtns = document.querySelectorAll(".tab-btn");
const tabs = document.querySelectorAll(".gallery");
tabBtns.forEach(function (btn, i) {
btn.addEventListener("click", function () {
if (tabs[i].classList.contains("hidden")) {
tabs[i].classList.toggle("hidden");
tabs[Math.abs(i - 1)].classList.toggle("hidden");
}
});
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
@font-face {
font-family: "Roboto", sans-serif;
src: url("Roboto-Bold-webfont.woff") format("woff");
font-style: normal;
font-weight: 700;
}
@font-face {
font-family: "Roboto", sans-serif;
src: url("Roboto-Regular-webfont.woff") format("woff");
font-style: normal;
font-weight: 400;
}
body {
width: 100%;
font-family: "Roboto", sans-serif;
font-size: 15px;
line-height: 1.5em;
}
.page {
display: flex;
justify-content: space-around;
margin-top: 50px;
}
.sidebar {
display: flex;
justify-content: flex-start;
flex-direction: column;
align-items: center;
position: fixed;
top: 100px;
left: 50px;
width: 400px;
/* border: 1px solid red; */
}
.sidebar-button {
display: flex;
align-items: center;
justify-content: center;
width: 400px;
}
.sidebar img {
height: 200px;
}
.content {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin: 50px 0 0 400px;
/* border: 1px solid red; */
}
.page-tab {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}
.tab-btn {
display: flex;
justify-content: center;
align-items: center;
width: 300px;
}
.sidebar-button,
.tab-btn {
margin: 10px;
height: 45px;
background-color: #d99023;
border-radius: 5px;
border: none;
cursor: pointer;
color: #ffffff;
font-family: "Roboto", sans-serif;
font-weight: 700;
font-size: 20px;
}
.sidebar-button:hover,
.tab-btn:hover {
background-color: #9c5400;
}
.sidebar-button a {
text-decoration: none;
color: #ffffff;
}
.page-tab button:active {
background-color: #9c5400;
color: #ffffff;
}
.gallery {
display: flex;
justify-content: center;
flex-wrap: wrap;
padding-top: 50px;
}
.gallery img {
height: 350px;
}
.hidden {
display: none;
}
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<meta name = "viewport" content = "width=device-width, initial-scale=1.0">
<script src = "/script.js" defer></script>
<link rel = "stylesheet" href = "/style.css">
<title>Document</title>
</head>
<body>
<div class = "page">
<nav class = "sidebar">
<img src = "images/logo.png" alt = "">
<button class = "sidebar-button">
<a href = "home.html">Home</a>
</button>
<button class = "sidebar-button">
<a href = "commissions.html">Commission</a>
</button>
<button class = "sidebar-button">
<a href = "about.html">About & Contact</a>
</button>
</nav>
<div class = "content">
<nav class = "page-tab">
<button class = "tab-btn" id = "btn-character-design">
Character Design
</button>
<button class = "tab-btn" id = "btn-illustration">
Illustration
</button>
</nav>
<div id = "tab-character-design" class = "gallery">
<img src = "images/poufdesign1.png" alt = "" class = "gallery-img">
<img src = "images/poufdesign2.png" alt = "" class = "gallery-img">
<img src = "images/poufdesign3.png" alt = "" class = "gallery-img">
<img src = "images/fairy-ring.png" alt = "" class = "gallery-img">
<img src = "images/luminae.png" alt = "" class = "gallery-img">
<img src = "images/griffoy.png" alt = "" class = "gallery-img">
<img src = "images/pokemon.png" alt = "" class = "gallery-img">
</div>
<div id = "tab-illustration" class = "gallery hidden">
<img src = "images/eloa-growth2.png" alt = "" class = "gallery-img">
<img src = "images/eloa-growth1.png" alt = "" class = "gallery-img">
<img src = "images/seviper-zangoose.png" alt = "" class = "gallery-img">
</div>
</div>
</div>
</body>
</html>
Я также внес небольшие изменения в код HTML и CSS (классы и идентификаторы). Итак, вы можете заменить свой код HTML и CSS на HTML и CSS решения.
как только вы нажмете одну из кнопок «вкладки», вы
display:none
ВСЕimg
теги — следовательно, никакого контента