#javascript #html #css
#javascript #HTML #css
Вопрос:
Я пытаюсь создать веб-сайт. И на моем веб-сайте, на странице меню, я хочу, чтобы мои параметры меню меняли цвет в зависимости от того, на какой из них был нажат. Например, когда страница загружается, она автоматически запускается на главной, поэтому главная кнопка зеленая. Но когда я нажимаю vegoption, я хочу, чтобы vegoption стал зеленым, а mainoption — черным. И та же система для других вариантов. Пожалуйста, простите меня, если я что-то сделал неправильно в своем javascript. Я очень новичок в этом языке. Если есть какие-либо другие улучшения, которые я могу внести, пожалуйста, дайте мне знать.
Вот код:
/* Start Variables */
:root {
--aa-color: #57C324;
}
/* End Variables */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Source Sans Pro', sans-serif;
}
/* Start Navbar */
.navbar-wrapper {
// background: blue;
padding: 20px 20px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 5px 10px 8px #888888;
z-index: 100;
position: relative;
}
.leftside {
// background: green;
width: 50%;
height: 10px;
}
.rightside {
width: 50%;
// background: red;
}
.options {
// background: yellow;
text-decoration: none;
width: 100%;
display: flex;
justify-content: flex-end;
}
.linkhome {
font-size: 120%;
text-decoration: none;
color: black;
margin-right: 0%;
margin-left: 2%;
display: inline-block;
}
.linkmenu {
font-size: 120%;
text-decoration: none;
color: var(--aa-color);
;
margin-right: 0%;
margin-left: 2%;
display: inline-block;
}
.linkabout {
font-size: 120%;
text-decoration: none;
color: black;
margin-right: 0%;
margin-left: 2%;
display: inline-block;
}
.linkfood {
font-size: 120%;
text-decoration: none;
color: black;
margin-right: 0%;
margin-left: 2%;
display: inline-block;
}
.linkculture {
font-size: 120%;
text-decoration: none;
color: black;
margin-right: 0%;
margin-left: 2%;
display: inline-block;
}
.linkmenu:hover {
color: var(--aa-color);
}
.linkabout:hover {
color: var(--aa-color);
}
.linkfood:hover {
color: var(--aa-color);
}
.linkculture:hover {
color: var(--aa-color);
}
/* End Navbar */
/* Start Main */
.injera-menu {
background-size: cover;
overflow: hidden;
width: 100%;
height: 10%;
display: block;
}
.ourmenutext {
position: absolute;
margin-top: -25%;
font-size: 400%;
background: -webkit-linear-gradient(#10CB00, #10CB00, #FFC701, #FF0101, #FF0101);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
-webkit-text-stroke: 3px white;
-webkit-text-stroke: 3px black;
margin-left: 3%;
}
.menuoptions {
display: flex;
width: 100%;
justify-content: center;
}
.mainoption {
margin: 2% 5%;
color: var(--aa-color);
}
.vegoption {
margin: 2% 5%;
}
.specialoption {
margin: 2% 5%;
}
.drinksoption {
margin: 2% 5%;
}
.vegoption:hover {
color: var(--aa-color)
}
.specialoption:hover {
color: var(--aa-color)
}
.drinksoption:hover {
color: var(--aa-color)
}
/* Start Menu */
.menu {
position: relative;
}
/* Start Main Menu */
.menumain {
justify-content: center;
color: var(--aa-color);
dis
}
.price {
float: right;
border: 1px solid var(--aa-color);
padding: 1% 2%;
}
.dishtitle {
margin-left: 40%;
text-decoration: underline;
}
.dishinfo {
padding: 5% 10%;
font-size: 150%;
}
.menu-item {
width: 70%;
border: 3px solid var(--aa-color);
padding: 20px;
margin-left: 15%;
margin-bottom: 5%;
box-shadow: 5px 10px 8px #888888;
justify-content: center;
}
.menuveg {
width: 100%;
justify-content: center;
color: var(--aa-color);
display: none;
}
.one-pers, .two-pers, .three-pers, .four-pers{
margin: 4% 40%;
display: flex;
}
.perstext{
width: 50%;
margin-right: 20%;
}
.persprice{
width: 50%;
float: left;
}
.menuspecial {
width: 100%;
justify-content: center;
color: var(--aa-color);
display: none;
}
.dishinfo2 {
padding: 5% 10%;
font-size: 150%;
text-decoration: none;
text-align: center;
}
/* End Menu */
/* End Main */
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Addis Abeba | Menu</title>
<link rel="stylesheet" href="/css/menu.css">
<link href="https://fonts.googleapis.com/css2?family=Source Sans Pro:wght@900amp;display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Source Sans Pro:wght@300amp;display=swap" rel="stylesheet">
</head>
<body>
<!-- Start Navbar -->
<nav>
<div class="navbar-wrapper">
<div class="leftside">
</div>
<div class="rightside">
<div class="options">
<a href="#" class="linkhome">Home</a>
<a href="menu.html" class="linkmenu">Menu</a>
<a href="#" class="linkabout">About Us</a>
<a href="#" class="linkfood">Our Food</a>
<a href="#" class="linkculture">Ethiopian Culture</a>
</div>
</div>
</div>
</nav>
<!-- End Navbar -->
<!-- Start Main -->
<div class="our-menu">
<div class="ourmenusection">
<div class="img1">
<img src="img/injera.png" alt="injera" class="injera-menu">
</div>
<div class="text-ourmenu">
<h1 class="ourmenutext">
Menu</h1>
</div>
</div>
</div>
<div class="menuoptions">
<h2 class="mainoption">Main</h2>
<h2 class="vegoption" onclick="showveg()">Vegetarian</h2>
<h2 class="specialoption" onclick="showspecial()">Special</h2>
<h2 class="drinksoption" onclick="showspecial()">Drinks</h2>
</div>
<div class="menu">
<!-- Start Main Menu -->
<div class="menumain">
<div class="menu-item">
<div class="price">
<p>CHF 21.-</p>
</div>
<div class="dishtitle">
<h1>Key Wat</h1>
</div>
<div class="dishinfo">
Tender morsels of meat prepared in specially spiced butter, seasoned with onions and green peppers, sprinkled with garlic and ginger.
</div>
</div>
<div class="menu-item">
<div class="price">
<p>CHF 23.-</p>
</div>
<div class="dishtitle">
<h1>Doro Wat</h1>
</div>
<div class="dishinfo">
Chicken cooked in specially seasoned red sauce and Ethiopian butter.
</div>
</div>
<div class="menu-item">
<div class="price">
<p>CHF 23.-</p>
</div>
<div class="dishtitle">
<h1>Yebeg Wat</h1>
</div>
<div class="dishinfo">
Morsels of lamb prepared in special herb butter, seasoned with onions and green peppers and sprinkled with garlic and ginger.
</div>
</div>
<div class="menu-item">
<div class="price">
<p>CHF 25.-</p>
</div>
<div class="dishtitle">
<h1>Kitfo</h1>
</div>
<div class="dishinfo">
Steak tartare, Ethiopian style, seasoned with special hot red pepper and spiced butter
</div>
</div>
<div class="menu-item">
<div class="price">
<p>CHF 24.-</p>
</div>
<div class="dishtitle">
<h1>Beef Tibs</h1>
</div>
<div class="dishinfo">
Strips of beef sauteed with onion and pepper.
</div>
</div>
<div class="menu-item">
<div class="price">
<p>CHF 24.-</p>
</div>
<div class="dishtitle">
<h1>Lamb Tibs</h1>
</div>
<div class="dishinfo">
Cubes of lamb fried in buter, onions, green and black peppers.
</div>
</div>
</div>
<!-- Start Vegetarian Menu -->
<div class="menuveg">
<div class="menu-item">
<div class="price">
<p>CHF 17.-</p>
</div>
<div class="dishtitle">
<h1>Shiro</h1>
</div>
<div class="dishinfo">
Yellow split peas cooked in special sauce and blended into a puree flavored with spices.
</div>
</div>
<div class="menu-item">
<div class="price">
<p>CHF 17.-</p>
</div>
<div class="dishtitle">
<h1>Misir</h1>
</div>
<div class="dishinfo">
Cracked lentil cooked in spiced sauce.
</div>
</div>
<div class="menu-item">
<div class="price">
<p>CHF 16.-</p>
</div>
<div class="dishtitle">
<h1>Gomen</h1>
</div>
<div class="dishinfo">
Assortment of spicy chopped vegetables cooked in spiced butter, onions and various kinds of exotic peppers.
</div>
</div>
<div class="menu-item">
<div class="dishtitle" style="margin-left: 30%;">
<h1>Vegetarian Tasting Menu</h1>
</div>
<div class="pers">
<div class="one-pers">
<div class="perstext">
<h3>1 Pers</h3>
</div>
<div class="persprice">
<div class="price">
<p>CHF 22.-</p>
</div>
</div>
</div>
<div class="two-pers">
<div class="perstext">
<h3>2 Pers</h3>
</div>
<div class="persprice">
<div class="price">
<p>CHF 44.-</p>
</div>
</div>
</div>
<div class="three-pers">
<div class="perstext">
<h3>3 Pers</h3>
</div>
<div class="persprice">
<div class="price">
<p>CHF 66.-</p>
</div>
</div>
</div>
<div class="four-pers">
<div class="perstext">
<h3>4 Pers</h3>
</div>
<div class="persprice">
<div class="price">
<p>CHF 88.-</p>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Start Special Menu -->
<div class="menuspecial">
<div class="menu-item">
<div class="dishtitle">
<h1>Addis Abeba Special</h1>
</div>
<div class="dishinfo2">
<h3>Includes:</h3>
Tibs, Yebuegue Alicha, Doro Woot and choice of Lentils or Vegetables
</div>
<div class="pers">
<div class="two-pers">
<div class="perstext">
<h3>2 Pers</h3>
</div>
<div class="persprice">
<div class="price">
<p>CHF 52.-</p>
</div>
</div>
</div>
<div class="three-pers">
<div class="perstext">
<h3>3 Pers</h3>
</div>
<div class="persprice">
<div class="price">
<p>CHF 78.-</p>
</div>
</div>
</div>
<div class="four-pers">
<div class="perstext">
<h3>4 Pers</h3>
</div>
<div class="persprice">
<div class="price">
<p>CHF 99.-</p>
</div>
</div>
</div>
</div>
</div>
<div class="menu-item">
<div class="dishtitle">
<h1>Tasting Menu</h1>
</div>
<div class="dishinfo2">
<h3>Includes:</h3>
Tibs, Yebuegue Alicha, Doro Woot, Kitfo and choice of Lentils or Vegetables
</div>
<div class="pers">
<div class="two-pers">
<div class="perstext">
<h3>2 Pers</h3>
</div>
<div class="persprice">
<div class="price">
<p>CHF 60.-</p>
</div>
</div>
</div>
<div class="three-pers">
<div class="perstext">
<h3>3 Pers</h3>
</div>
<div class="persprice">
<div class="price">
<p>CHF 90.-</p>
</div>
</div>
</div>
<div class="four-pers">
<div class="perstext">
<h3>4 Pers</h3>
</div>
<div class="persprice">
<div class="price">
<p>CHF 115.-</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End Main -->
<!-- Start JS -->
<script type="text/javascript">
function showmain() {
document.getElementsByClassName("menumain")[0].style.display = "inline-block";
document.getElementsByClassName("menuveg")[0].style.display = "none";
document.getElementsByClassName("menuspecial")[0].style.display = "none";
document.getElementsByClassName("menudrinks")[0].style.display = "none";
document.getElementsByClassName("mainoption")[0].style.color = "#57C324";
document.getElementsByClassName("vegoption")[0].style.color = "black";
document.getElementsByClassName("specialoption")[0].style.color = "black";
document.getElementsByClassName("drinksoption")[0].style.color = "black";
}
function showveg() {
document.getElementsByClassName("menumain")[0].style.display = "none";
document.getElementsByClassName("menuveg")[0].style.display = "inline-block";
document.getElementsByClassName("menuspecial")[0].style.display = "none";
document.getElementsByClassName("menudrinks")[0].style.display = "none";
document.getElementsByClassName("mainoption")[0].style.color = "black";
document.getElementsByClassName("vegoption")[0].style.color = "#57C324";
document.getElementsByClassName("specialoption")[0].style.color = "black";
document.getElementsByClassName("drinksoption")[0].style.color = "black";
}
function showspecial() {
document.getElementsByClassName("menumain")[0].style.display = "none";
document.getElementsByClassName("menuveg")[0].style.display = "none";
document.getElementsByClassName("menuspecial")[0].style.display = "inline-block";
document.getElementsByClassName("menudrinks")[0].style.display = "none";
document.getElementsByClassName("mainoption")[0].style.color = "black";
document.getElementsByClassName("vegoption")[0].style.color = "black";
document.getElementsByClassName("specialoption")[0].style.color = "#57C324";
document.getElementsByClassName("drinksoption")[0].style.color = "black";
}
function showdrinks() {
document.getElementsByClassName("menumain")[0].style.display = "none";
document.getElementsByClassName("menuveg")[0].style.display = "none";
document.getElementsByClassName("menuspecial")[0].style.display = "none";
document.getElementsByClassName("menudrinks")[0].style.display = "inline-block";
document.getElementsByClassName("mainoption")[0].style.color = "black";
document.getElementsByClassName("vegoption")[0].style.color = "black";
document.getElementsByClassName("specialoption")[0].style.color = "black";
document.getElementsByClassName("drinksoption")[0].style.color = "#57C324";
}
</script>
<!-- End JS -->
</body>
</html>
Любая помощь будет очень признательна.
Спасибо!
Комментарии:
1. В ваших
:hover
определениях укажите шестнадцатеричный код цвета, а не ссылку на--aa-color
2. я не уверен, принимаете ли вы ответы на jquery, но я немного переписал код: jsfiddle.net/vwekud8a
Ответ №1:
Если вы не используете фреймворк, я бы все равно предложил использовать jQuery, особенно потому, что, на мой взгляд, он очень удобен для начинающих.
Последнюю версию jQuery можно найти здесь. Вы можете просто связать его в своем HTML-файле следующим образом:
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
</head>
С помощью jQuery вы можете установить события для щелчка по объекту.
Примером события щелчка для одного из ваших классов может быть что-то вроде этого:
$(".vegoption").click(function(){
// do something when .vegoption is clicked
})
Если вы хотите изменить его цвет при нажатии, вы можете просто вызвать .css(), чтобы изменить цвет фона следующим образом:
$(".vegoption").click(function(){
$(this).css("background-color", "green");
})
Если вы хотите, чтобы определенный класс был окрашен в зеленый цвет при переходе на страницу, вы можете вызвать $(document).ready()
событие, которое входит в состав jQuery и вызывает все в рамках своей функции, как только страница загрузится правильно.
$(document).ready(function(){
$(".mainoption").css("background-color", "green");
})
Чтобы убедиться, что только один параметр является зеленым одновременно, вы можете просто изменить цвет всех других параметров обратно на их значения по умолчанию в рамках этих событий, как описано в примерах выше.
Комментарии:
1. @SiannaZewdie Добро пожаловать, рад помочь другу-швейцарцу 🙂