Методы массивов: накопление и цепочки
Чтение — около 5 минут· без учёта практики
Как посчитать стоимость корзины
Для примера возьмём заказ из трёх мячей по 450 рублей и двух поводков по 890. Каждая позиция в массиве
cart — объект с названием name, ценой одной штуки price и количеством
quantity. В
предыдущем уроке
мы искали отдельный товар, а для чека сложим стоимость всех позиций. В своей Лавке тем же способом сложим остатки на
складе.
При подсчёте суммы вручную удобно завести накопитель — переменную с промежуточным итогом. Начинаем с нуля и для каждой позиции прибавляем цену, умноженную на количество. Вот как выглядит знакомый цикл:
const cart = [
{ name: "Мяч", price: 450, quantity: 3 },
{ name: "Поводок", price: 890, quantity: 2 }
];
let sum = 0;
for (const item of cart) {
sum += item.price * item.quantity;
}
console.log(sum); // 3130Один итог через reduce
Метод
reduce()
берёт на себя перебор корзины. Нам остаётся задать начальную сумму и правило прибавления стоимости одной позиции.
Назовём функцию с этим правилом addItemTotal. Посмотрите, где в вызове передаётся функция, а где —
начальное значение.
При первом вызове addItemTotal(sum, item) получает 0 и объект мяча. Инструкция
return sum + item.price * item.quantity вернёт 1350. Именно это число
reduce() передаст как sum при вызове для поводка.
Возвращайте накопитель на каждом шаге
Проследите за накопителем после каждого товара и предскажите сумму. Измените количество мячей на 1 и пересчитайте её. Как повлияет начальное значение, если корзина пуста?
index.html
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Общая стоимость корзины</title>
</head>
<body>
<h1>Общая стоимость корзины</h1>
<script src="script.js"></script>
</body>
</html>
script.js
const cart = [
{ name: "Мяч", price: 450, quantity: 3 },
{ name: "Поводок", price: 890, quantity: 2 }
];
function addItemTotal(sum, item) {
return sum + item.price * item.quantity;
}
const total = cart.reduce(addItemTotal, 0);
console.log(total);
Последнее значение накопителя попадёт в total. Сверьте расчёт в таблице с выводом программы, а затем
проверьте, каким станет итог, если в корзине останется один мяч и два поводка.
| Запись | sum до | Возвращаемый итог |
|---|---|---|
| Мяч: 450 × 3 | 0 |
1350 |
| Поводок: 890 × 2 | 1350 |
3130 |
Для этой суммы явно передаём 0. Без начального значения метод взял бы первый элемент как накопитель, а
это объект товара, не число. У пустого массива reduce без начального значения вызывает
TypeError. С начальным нулём пустая корзина даёт ноль без вызова callback.
Ту же функцию можно записать прямо в скобках как стрелочную. На схеме проследите, как результат одного вызова становится первым аргументом следующего.
В тренажёре ниже элементы уже представлены числами. Попробуйте пустой массив и проследите, как начальное значение попадает в результат, когда прибавлять нечего.
Цепочка методов: результат становится входом
В цепочке catalog.filter(...).map(...).reduce(...) сначала filter обрабатывает весь исходный
массив. Затем map получает только отобранные элементы, а reduce — уже преобразованные. Это
последовательные проходы, а не выполнение трёх callback подряд для каждого исходного элемента. Индексы callback
отсчитываются заново в массиве текущего метода.
Посчитаем стоимость игрушек на складе. Отберём товары в наличии, для каждого умножим цену на остаток, затем сложим
стоимости с начальным накопителем 0. Если отбор ничего не оставил, callback у map и
reduce не вызываются, а итог равен 0. Исходный массив сохраняется, потому что эти callback не меняют его.
Запишем цепочку по шагам, сохранив промежуточные массивы в переменных:
const catalog = [
{ name: "Мяч для прогулок", price: 450, stock: 15 },
{ name: "Канат «Удав»", price: 490, stock: 8 },
{ name: "Кольцо «Апорт»", price: 450, stock: 0 }
];
// Оставляем только товары, которые есть на складе.
const selected = catalog.filter(product => product.stock > 0);
// Для каждого товара умножаем цену за штуку на количество штук на складе.
const values = selected.map(product => product.price * product.stock);
// Складываем полученные стоимости, начиная с нуля.
const total = values.reduce((sum, value) => sum + value, 0);
console.log(total);| Шаг | Получает | Возвращает |
|---|---|---|
filter(…) |
Мяч, канат, кольцо | Мяч и канат |
map(…) |
Мяч и канат | [6750, 3920] |
reduce(…, 0) |
[6750, 3920] |
10670 |
Теперь уберём промежуточные переменные. Точка в начале строки продолжает предыдущее выражение: следующий метод
вызывается у результата предыдущего. После reduce здесь уже число.
Проследите, какие числа дойдут до сложения
Запустите цепочку и сверьте итог с таблицей. Затем обнулите остаток каната, а после — и мяча. Какой результат даст пустой отбор?
index.html
<html lang="ru">
<head>
<meta charset="utf-8">
<title>От списка чисел к одной сумме</title>
</head>
<body>
<h1>От списка чисел к одной сумме</h1>
<script src="script.js"></script>
</body>
</html>
script.js
const catalog = [
{ name: "Мяч для прогулок", price: 450, stock: 15 },
{ name: "Канат «Удав»", price: 490, stock: 8 },
{ name: "Кольцо «Апорт»", price: 450, stock: 0 }
];
const total = catalog
.filter(product => product.stock > 0)
.map(product => product.price * product.stock)
.reduce((sum, value) => sum + value, 0);
console.log(total);
Коротко
-
reduce((acc, item) => …, начальное)сводит массив к одному итогу. Результат callback становится накопителем следующего шага. -
Для суммы передайте начальное значение
0. Тогда пустой массив тоже даст сумму0. Без начального значения вызов на пустом массиве завершится ошибкойTypeError. - В цепочке
filter → map → reduceкаждый метод получает весь результат предыдущего. - Если итог не сходится, разбейте цепочку на переменные и проверьте промежуточные массивы.
Случай с пустым массивом отдельно разобран в справочнике ошибок:
Reduce of empty array with no initial value.
Проверьте себя
Выберите ответ — объяснение появится сразу. Ответ можно менять.
Задания
Задание. Проект «Лавка Тони» — посчитайте общий остаток
На одном и том же складе у мяча 15 штук, у каната 8, у кольца 0. Сколько игрушек всего?
Эти же шаги можно выполнить в своей папке.
-
В
js/shop.jsперед объявлениемcartDialogдобавьте функциюcountStock(products). Вызовитеreduceс начальным значением 0. На каждом шаге прибавляйте к накопителюproduct.stock. -
Выведите
countStock(catalog). Предскажите результат для пустого массива, затем проверьте его отдельным вызовом.
Проверьте результат. Склад даёт 23 штуки, пустой массив — 0. Если временно прибавить единицу к остатку каната, итог увеличится до 24.
Проверьте свою Лавку
Условие задания
js/shop.js
/*
Лавка Тони: программа магазина.
Разделы: товары, заказ, проверки и чек.
*/
console.log("Лавка Тони");
// Товары
const productName = "Мяч для прогулок";
const price = 450;
const isAvailable = true;
const isFavorite = false;
const description = "";
const ropeName = "Канат «Удав»";
const ropePrice = 490;
const ropeStock = 8;
// Заказ
const quantityText = "3";
const quantity = Number(quantityText);
const selectedProduct = null;
const promoCode = null;
let pickupPoint;
const pickupCost = 0;
const deliveryText = "150";
const savedDelivery = 0;
const delivery = savedDelivery ?? Number(deliveryText);
const savedName = "";
const customerName = savedName || "Гость";
const paid = 2000;
const hasCard = false;
const hasCash = true;
const isBlocked = false;
const isPaid = true;
const payOnPickup = true;
// Склад
const incoming = 5;
const packSize = 4;
let stock = 12;
stock += incoming;
stock -= quantity;
stock++;
const unpacked = stock % packSize;
// Чек заказа
function calcTotal(itemPrice, itemQuantity, itemDelivery = 150) {
if (itemQuantity <= 0) {
return 0;
}
return itemPrice * itemQuantity + itemDelivery;
}
const subtotal = price * quantity;
const total = calcTotal(price, quantity, delivery);
const change = paid - total;
function printReceipt() {
console.log(`Товары: ${subtotal}`);
console.log(`К оплате: ${total}`);
console.log(`Сдача: ${change}`);
}
console.log("Чек покупателю");
printReceipt();
console.log("Копия для склада");
printReceipt();
// Проверки заказа
const freeDeliveryFrom = 1000;
const selectedName = "Мяч для прогулок";
const hasEnough = stock >= quantity;
const hasFreeDelivery = subtotal >= freeDeliveryFrom;
const sameName = selectedName === productName;
const validQuantity = quantity > 0 && quantity <= stock;
const canPay = hasCard || hasCash;
const canOrder = validQuantity && canPay && !isBlocked;
let message = "";
if (isBlocked) {
message = "Заказ недоступен";
} else if (!hasEnough) {
message = "Недостаточно товара";
} else if (isPaid) {
message = "Передаём заказ в доставку";
} else {
message = "Ожидаем оплату";
}
// Подписи
const productCode = "B17";
const card = `${productName} — ${price} руб.`;
const badge = productName[0] + "-" + productCode;
// Признаки товара
const hasDescription = Boolean(description);
// Скидка на каждый мяч
const discountPerItem = 50;
const discountedTotal = (price - discountPerItem) * quantity + delivery;
const canCheckout = hasEnough && (isPaid || payOnPickup);
// Способ получения и наличие
const isPickup = delivery === 0;
const methodLabel = "Способ: " + (isPickup ? "Самовывоз" : "Доставка");
const stockLabel = isAvailable ? "В наличии" : "Закончился";
// Способ получения по коду из формы
const methodText = "1";
const methodCode = Number(methodText);
let methodName = "";
let methodCost = null;
switch (methodCode) {
case 1:
methodName = "Самовывоз";
methodCost = 0;
break;
case 2:
case 3:
methodName = "Доставка";
methodCost = 150;
break;
default:
methodName = "Неизвестный способ";
methodCost = null;
break;
}
// Упаковка заказа
const boxCapacity = 2;
let remaining = quantity;
let boxes = 0;
while (remaining > 0) {
if (remaining > boxCapacity) {
remaining -= boxCapacity;
} else {
remaining = 0;
}
boxes++;
}
// Подарки к заказам: Тони дарит мячик каждому чётному заказу дня
const lastOrder = 10;
const giftsEndAt = 8;
let giftCount = 0;
let giftSum = 0;
for (let orderNumber = 1; orderNumber <= lastOrder; orderNumber++) {
if (orderNumber === giftsEndAt) {
break;
}
if (orderNumber % 2 !== 0) {
continue;
}
giftSum += orderNumber;
giftCount++;
}
// Проверка calcTotal
console.log(calcTotal(ropePrice, 2));
console.log(calcTotal(price, 2, 0));
console.log(calcTotal(price, 0, 150));
// Данные первого товара
const ball = {
id: "ball",
name: productName,
price: price,
stock: stock,
priceLabel() {
return this.price + " ₽";
}
};
console.log(ball.priceLabel());
const rope = { id: "rope", name: ropeName, price: ropePrice, stock: ropeStock };
const ring = { id: "ring", name: "Кольцо «Апорт»", price: 450, stock: 0 };
const catalog = [ball, rope, ring];
console.log(catalog.length);
for (const product of catalog) {
console.log(product.name);
}
// Пробная цена для подарка
const gift = { id: rope.id, name: rope.name, price: rope.price };
gift.price = 0;
console.log(gift.price, rope.price);
function offerPrice(product) {
return product.offer?.price ?? product.price;
}
console.log(offerPrice(rope));
console.log(offerPrice({ price: rope.price, offer: { price: 0 } }));
function availableProducts(products) {
return products.filter(product => product.stock > 0);
}
console.log(availableProducts(catalog).map(product => product.name));
function findProduct(id) {
return catalog.find(product => product.id === id);
}
console.log(findProduct("rope")?.name ?? "Товар не найден");
console.log(findProduct("cat")?.name ?? "Товар не найден");
const cartDialog = document.querySelector("#cart-dialog");
const openCart = document.querySelector("#open-cart");
const closeCart = document.querySelector("#close-cart");
openCart.addEventListener("click", () => cartDialog.showModal());
closeCart.addEventListener("click", () => cartDialog.close());
cartDialog.addEventListener("close", () => openCart.focus());
document.querySelector(".product h3").textContent = ball.name;
document.querySelector(".product .price").textContent = ball.priceLabel();
const cart = [];
const cartCount = document.querySelector("#cart-count");
cartCount.textContent = cart.length;
const cartItems = document.querySelector("#cart-items");
function addBall() {
cart.push(ball.id);
cartCount.textContent = cart.length;
cartItems.textContent = findProduct(cart[cart.length - 1]).name + " × " + cart.length;
}
document.querySelector(".product .add").addEventListener("click", addBall);
index.html
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Лавка Тони — учебный магазин игрушек и вещей для собак.">
<title>Лавка Тони</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/shop.css">
</head>
<body class="shop">
<a class="skip" href="#catalog">К товарам</a>
<main>
<section class="shop-hero" aria-labelledby="shop-title">
<div><p class="eyebrow">Маленькая лавка большого друга</p><h1 id="shop-title">Для игр, прогулок<br>и сладких снов.</h1>
<p>Привет, это Тони! Готовлю лавку игрушек и вещей для наших собачьих дел.</p>
<a class="shop-link" href="#catalog">Заглянуть в лавку ↓</a><p class="muted">Учебный магазин · без оплаты и настоящих заказов</p></div>
<figure><img src="assets/tony-toy.png" alt="Тони со своим любимым канатом" width="300" height="400"><figcaption>Главный по проверке игрушек</figcaption></figure>
</section>
<section id="catalog" aria-labelledby="catalog-title">
<div class="section-heading"><div><p class="eyebrow">Выбрано с лапой</p><h2 id="catalog-title">Лавка Тони</h2></div>
<button id="open-cart" type="button">Корзина · <span id="cart-count">0</span></button>
</div>
<p id="catalog-status" role="status">Первый товар в Лавке.</p>
<div id="products" class="products">
<article class="product" data-id="ball">
<div class="product-art"><img src="assets/ball.svg" alt="Мяч для прогулок" width="300" height="240"></div>
<div class="product-body">
<h3></h3>
<div class="product-bottom"><strong class="price"></strong>
<button class="add" type="button">В корзину</button>
</div>
</div>
</article>
</div>
</section>
</main>
<footer><p>© 2026 Тони и его хозяин · Сделано для любопытных</p></footer>
<dialog id="cart-dialog" aria-labelledby="cart-title">
<div class="section-heading">
<h2 id="cart-title">Твоя корзина</h2>
<button id="close-cart" type="button" class="secondary">Закрыть</button>
</div>
<div id="cart-items">В корзине пока пусто. Тони советует начать с игрушки.</div>
</dialog>
<script src="js/shop.js"></script>
</body>
</html>
css/style.css
/* Все обычные правила проекта распределены по слоям. */
@layer base, layout, components;
@layer base {
/* Общие стили сайта Тони */
/* Ширина и высота включают внутренние отступы и рамку — у всех элементов и псевдоэлементов */
*,
*::before,
*::after {
box-sizing: border-box;
}
/* Палитра сайта в пользовательских свойствах: цвет меняется в одном месте */
:root {
--accent: saddlebrown; /* заголовки, меню, акценты */
--text: #2b211b; /* основной текст */
--text-muted: #6b5d52; /* подписи и второстепенный текст */
}
/* Шрифт заголовков Nunito (лицензия SIL Open Font License): кириллица и латиница в разных файлах */
@font-face {
font-family: "Nunito";
src: url("../assets/nunito-cyrillic-800-normal.woff2") format("woff2");
font-weight: 800;
font-display: swap; /* пока шрифт загружается, текст виден запасным шрифтом */
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: "Nunito";
src: url("../assets/nunito-latin-800-normal.woff2") format("woff2");
font-weight: 800;
font-display: swap;
unicode-range: U+0000-00FF, U+2000-206F, U+20AC, U+2122;
}
body {
background-color: linen;
color: var(--text); /* цвет для потомков без собственного значения */
font-size: 1.0625rem; /* 17px при настройке браузера по умолчанию */
font-family:
system-ui,
-apple-system,
"Segoe UI",
Roboto,
sans-serif; /* системный шрифт устройства */
line-height: 1.6; /* множитель: у каждого элемента интервал от его собственного размера шрифта */
margin: 0; /* убираем отступ браузера: шапка и подвал во всю ширину окна */
}
/* Поля основного содержимого: текст не прижимается к краям окна */
/* Изображения и видео не шире колонки, пропорции сохраняются */
img,
video {
max-width: 100%;
height: auto;
}
/* Фреймы, аудиоплеер и поля формы не выходят за колонку */
iframe,
audio,
input,
select,
textarea,
button {
max-width: 100%;
}
/* Разрешаем группе полей сужаться вместе с колонкой. */
fieldset {
min-width: 0;
}
/* Общий цвет заголовков — групповой селектор */
h1,
h2 {
color: var(--accent);
font-family: "Nunito", "Trebuchet MS", system-ui, sans-serif;
font-weight: 800;
line-height: 1.2; /* крупному тексту хватает меньшего интервала */
}
/* Размеры заголовков в rem — от размера шрифта корня, а не родителя */
h1 {
text-align: center;
font-size: 2.5rem;
}
h2 {
font-size: 1.75rem;
}
}
@layer layout {
main {
padding: 1.5rem 1rem;
max-width: 68rem; /* на широком экране строки не растягиваются на всё окно */
margin: 0 auto; /* колонка по центру */
}
}
@layer components {
/* Вводный блок главной страницы */
.intro {
background-color: hsl(30, 80%, 95%);
padding: 1.5rem; /* фон вокруг текста; заодно не выпускает margin заголовка за пределы блока */
border-radius: 16px; /* скругляется и фон, хотя рамки нет */
/* Лапка в правом нижнем углу; цвет фона выше остаётся запасным, если картинка не загрузится */
background-image: url("../assets/paw.svg");
background-repeat: no-repeat;
background-position: right 1rem bottom 1rem;
background-size: 4rem;
}
/* Разделы главной — светлые карточки на фоне страницы */
main > section {
background-color: var(--paper, #fffaf3);
border: 1px solid hsl(28, 30%, 82%);
border-radius: 16px;
padding: 1.5rem;
margin-top: 1.5rem;
}
/* Ширина вводных абзацев ограничена 60ch; количество букв в строке зависит от шрифта и текста */
.intro p {
max-width: 60ch;
}
/* Важное предупреждение во вводном блоке — темнее основного акцента */
.intro strong {
color: #6e3510;
}
/* Оглавление главной страницы — переносимый ряд «таблеток» на Flexbox */
.toc {
background-color: white;
border: 1px solid tan;
display: flex;
flex-wrap: wrap; /* «таблетки», которым не хватает места, переходят на новую строку */
gap: 0.5rem; /* промежутки между «таблетками» и между строками */
list-style: none;
padding: 0.75rem;
}
/* Подчёркивание ссылок чуть ниже букв: не задевает выносные элементы */
a {
text-underline-offset: 3px;
}
/* Тонкая линия отделяет шапку от страницы */
header {
border-bottom: 1px solid tan;
}
/* Меню в одну строку на Flexbox: пункты — флекс-элементы, промежутки задаёт gap */
nav ul {
margin: 0;
padding: 0.5rem 1rem;
display: flex;
gap: 0.5rem;
list-style: none;
}
/* Ссылка на запись стоит отдельно у правого края: автоматический отступ забирает свободное место */
nav li:last-child {
margin-left: auto;
}
/* Ссылки меню в шапке — селектор потомков */
nav a {
color: var(--accent);
text-decoration: none;
display: inline-block; /* у строчной ссылки вертикальный padding не раздвигает строку */
padding: 0.4rem 0.9rem;
border-radius: 999px; /* «таблетка»: радиус больше половины высоты */
}
/* Ссылки оглавления главной страницы */
.toc a {
color: var(--text-muted); /* тёплый серый: контраст 6.34:1 на белом фоне оглавления */
display: block; /* ссылка заполняет «таблетку» целиком */
padding: 0.25rem 0.75rem;
border: 1px solid tan;
border-radius: 999px;
text-decoration: none;
}
/* Фотографии со скруглёнными углами */
figure img {
border-radius: 8px;
}
figcaption {
color: var(--text-muted); /* тёплый серый: контраст 5.64:1 на фоне linen */
font-size: 0.95rem;
}
footer {
background-color: hsl(30, 50%, 90%);
text-align: center;
padding: 1rem;
}
/* Ссылка в подвале берёт цвет текста подвала */
footer a {
color: inherit;
}
/* Поля формы получают шрифт страницы вместо шрифта браузера */
input,
select,
textarea,
button {
font: inherit;
}
/* Ссылки темнеют при наведении указателя */
a:hover {
color: #5c2d0c;
}
/* Ссылки меню подчёркиваются при наведении и фокусе с клавиатуры */
nav a:hover,
nav a:focus-visible {
text-decoration: underline;
}
/* Заметная рамка фокуса у ссылок, полей и кнопок при работе с клавиатуры */
:focus-visible {
outline: 3px solid #1f6feb;
outline-offset: 3px;
}
/* Цитата из книги — шрифтом с засечками и курсивом */
blockquote {
font-family: Georgia, "Times New Roman", serif;
font-style: italic;
border-left: 4px solid tan; /* черта слева выделяет цитату */
padding-left: 1rem;
}
/* Подпись под цитатой — у правого края */
blockquote + figcaption {
text-align: right;
}
/* Строки формы на Flexbox: подпись — колонка постоянной ширины, поле занимает остаток строки,
а на узком экране переносится под подпись */
fieldset p {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1rem;
}
fieldset p label {
flex: 0 0 12rem; /* не растёт и не сжимается, исходная ширина 12rem */
}
fieldset p input,
fieldset p select,
fieldset p textarea {
flex: 1 1 12rem; /* растёт и сжимается от исходной ширины 12rem */
min-width: 0; /* поле может стать уже своего автоматического минимума */
}
/* Фотоальбом на Grid. Все правила альбома собраны во вложенный блок: & — сам .gallery */
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
gap: 1rem;
list-style: none;
padding: 0;
/* Карточка — точка отсчёта для значка */
& li {
position: relative;
}
/* Карточка со значком выделена рамкой */
& li:has(.badge) {
outline: 3px solid tan;
outline-offset: 4px;
border-radius: 8px;
}
& figure {
margin: 0;
}
& img {
width: 100%; /* фото заполняет ширину своей ячейки */
}
}
/* Список команд на Grid: термин в первой колонке шириной по самому длинному термину, описание — во второй */
dl {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 0.5rem 1rem;
}
dt {
grid-column: 1;
font-weight: bold;
}
dd {
grid-column: 2;
overflow-wrap: anywhere; /* длинный перевод переносится внутри своей колонки */
margin: 0; /* браузерный отступ слева больше не нужен: колонку задаёт сетка */
}
/* Длинные слова и адреса переносятся, а не выходят за край узкого экрана */
body {
overflow-wrap: break-word;
}
/* Таблица режима дня на узком экране прокручивается в своей рамке, а не сжимается до нечитаемых колонок */
.table-wrap {
overflow-x: auto;
}
table {
width: 100%;
min-width: 28rem;
}
/* Подпись таблицы прокручивается вместе с ней: прижимаем её к началу, чтобы она была видна сразу */
caption {
text-align: left;
}
/* Широкий экран: в разделе «Моя любимая игрушка» фото справа, текст слева.
На узком экране правило не действует, и раздел остаётся одной колонкой. */
@media (width >= 48rem) {
.toy {
display: grid;
grid-template-columns: minmax(0, 1fr) 300px;
column-gap: 1.5rem;
}
.toy figure {
grid-column: 2;
grid-row: 1 / span 6; /* фото рядом со всеми абзацами раздела */
margin: 0;
}
.toy hr {
width: 100%;
}
}
/* Значок «Любимая» в правом верхнем углу карточки; из потока исключён, поэтому фото не сдвигается */
.badge {
position: absolute;
top: 0.5rem;
right: 0.5rem;
padding: 0.2rem 0.7rem;
border-radius: 999px;
background-color: var(--accent);
color: white;
font-size: 0.85rem;
font-weight: bold;
}
/* Шапка прилипает к верхнему краю окна. Фон нужен, чтобы под шапкой не просвечивал текст страницы */
header {
position: sticky;
top: 0;
z-index: 10; /* выше карточек альбома: они тоже позиционированы и записаны в HTML позже шапки */
background-color: linen;
}
/* Липкая шапка должна быть низкой: пункты меню не сжимаются и не переносятся на вторую строку,
а если им не хватает места, меню прокручивается внутри шапки */
nav ul {
overflow-x: auto;
}
nav li {
flex-shrink: 0;
}
/* Заголовок, к которому ведёт ссылка-якорь, не прячется под липкой шапкой.
В rem: при увеличении текста растут и шапка, и отступ */
[id] {
scroll-margin-top: 4.5rem;
}
/* Ссылка, которая открывается в новой вкладке, помечена стрелкой — посетитель знает, что страница не сменится */
a[target="_blank"]::after {
content: " ↗";
}
/* Ссылка на электронную почту — с конвертом */
a[href^="mailto:"]::before {
content: "✉ ";
}
/* Первая ссылка меню — «Главная» — подписана лапкой без изменения HTML */
nav li:first-child a::before {
content: "🐾 ";
}
/* Первый абзац вводного блока крупнее остальных. :first-child здесь не подойдёт — первым стоит заголовок h1 */
.intro p:first-of-type {
font-size: 1.2rem;
}
/* Список игрушек: вместо стандартного кружка — косточка */
.toy-list li::marker {
content: "🦴 ";
}
/* Номера шагов в нумерованных списках — в цвет заголовков и жирные; текст пунктов не меняется */
ol li::marker {
color: var(--accent);
font-weight: bold;
}
/* Таблица режима дня: соседние рамки объединяются в одну линию */
table {
border-collapse: collapse;
}
/* Ячейки с воздухом и линией снизу; текст — от левого края и сверху, даже если в соседней ячейке две строки */
th,
td {
padding: 0.6rem 0.8rem;
border-bottom: 1px solid tan;
text-align: left;
vertical-align: top;
}
/* Шапка таблицы — в цвет заголовков сайта */
thead th {
background-color: var(--accent);
color: white;
}
/* Чётные строки тела таблицы — на светлом фоне: глаз не теряет строку */
tbody tr:nth-child(even) {
background-color: hsl(30, 80%, 95%);
}
/* Отдельные рамки без промежутков позволяют скруглить крайние ячейки. Линия только снизу не удваивается. */
table {
border-collapse: separate;
border-spacing: 0;
}
thead th:first-child {
border-top-left-radius: 8px;
}
thead th:last-child {
border-top-right-radius: 8px;
}
/* Форма записи: текстовые поля, список и область текста в едином стиле */
input:not([type="radio"], [type="checkbox"]),
select,
textarea {
padding: 0.5rem 0.75rem;
border: 1px solid #8a7660;
border-radius: 8px;
background-color: white;
}
/* Поле «Ведёт прогулку» менять нельзя — фон показывает это */
input[readonly] {
background-color: hsl(30, 80%, 95%);
}
/* Отмеченные флажки и переключатели — в цвет сайта */
input[type="radio"],
input[type="checkbox"] {
accent-color: var(--accent);
}
/* Неверно заполненное поле — после того как посетитель с ним поработал */
input:user-invalid,
select:user-invalid,
textarea:user-invalid {
border-color: firebrick;
}
/* Группы полей — светлые блоки с тонкой рамкой вместо рельефной рамки браузера */
fieldset {
margin-bottom: 1rem;
border: 1px solid #8a7660;
border-radius: 16px;
}
/* Группа полей, в которой сейчас работает посетитель */
fieldset:focus-within {
border-color: var(--accent);
}
/* Кнопки-«таблетки»: основная залита цветом, второстепенная — только рамка */
button {
padding: 0.7rem 1.4rem;
border: 2px solid var(--accent);
border-radius: 999px;
background-color: var(--accent);
color: white;
font-weight: bold;
cursor: pointer;
}
button[type="reset"] {
background-color: transparent;
color: var(--accent);
}
/* Текст ошибок связан с полями через aria-describedby и не полагается только на цвет рамки. */
.field-error {
display: none;
flex-basis: 100%;
color: firebrick;
font-weight: bold;
}
input:user-invalid + .field-error {
display: block;
}
/* Фото любимой игрушки — как карточка-полароид: слегка повёрнуто вокруг нижнего края, будто прижато к столу */
.toy img {
transform: rotate(-2deg);
transform-origin: 50% 100%;
}
/* Под указателем фото выпрямляется и чуть увеличивается */
.toy img:hover {
transform: rotate(0deg) scale(1.03);
}
/* «Таблетка» оглавления под указателем и в фокусе приподнимается: отдельное свойство translate */
.toc a:hover,
.toc a:focus-visible {
translate: 0 -2px;
}
/* Нажатая кнопка будто вдавливается */
button:active {
transform: translateY(1px) scale(0.98);
}
/* Плавные изменения: переходим конкретные свойства, а не all */
.toy img {
transition: transform 0.4s ease-out; /* фото выпрямляется плавно */
}
.toc a {
transition: translate 0.2s ease-out;
}
button {
transition:
background-color 0.2s,
transform 0.1s;
}
/* Посетитель попросил систему уменьшить движение — изменения происходят сразу, без переходов */
@media (prefers-reduced-motion: reduce) {
.toy img,
.toc a,
button {
transition: none;
}
}
/* Лапка у «Главной» машет, когда на ссылку наводят указатель */
@keyframes wag {
0%,
100% {
rotate: 0deg;
}
25% {
rotate: -18deg;
}
75% {
rotate: 18deg;
}
}
nav li:first-child a::before {
display: inline-block; /* строчный псевдоэлемент не поворачивается */
transform-origin: 50% 80%; /* лапка качается от «запястья» */
}
nav li:first-child a:hover::before,
nav li:first-child a:focus-visible::before {
animation-name: wag;
animation-duration: 0.5s;
animation-timing-function: ease-in-out;
animation-iteration-count: 2; /* помахать дважды и остановиться */
}
/* Приветствие на главной плавно появляется снизу при загрузке страницы */
@keyframes rise {
from {
opacity: 0;
translate: 0 16px;
}
/* to не задан: конечный кадр — обычный вид элемента */
}
.intro > * {
/* both: до старта — первый кадр (элемент скрыт во время задержки), после — последний */
animation: rise 0.6s ease-out both;
}
/* Строки появляются друг за другом */
.intro > :nth-child(2) {
animation-delay: 0.1s;
}
.intro > :nth-child(3) {
animation-delay: 0.2s;
}
.intro > :nth-child(4) {
animation-delay: 0.3s;
}
/* Посетитель попросил уменьшить движение — анимаций нет, всё видно сразу */
@media (prefers-reduced-motion: reduce) {
.intro > *,
nav li:first-child a:hover::before,
nav li:first-child a:focus-visible::before {
animation: none;
}
}
button:hover,
button:focus-visible {
background-color: #6b3513;
}
button[type="reset"]:hover,
button[type="reset"]:focus-visible {
background-color: hsl(30, 70%, 90%);
}
/* Подписи читаются на тёмной подложке и без декоративной тени. */
.gallery figcaption {
padding: 0.5rem;
color: white;
background-color: hsl(25, 50%, 15%);
text-shadow: 0 1px 3px rgb(0 0 0 / 60%);
}
/* Два слоя: чёткая тень у края и широкая мягкая тень под карточкой. */
.gallery li {
background-color: #fffaf3;
border-radius: 12px;
box-shadow: 0 1px 2px rgb(0 0 0 / 8%), 0 8px 24px rgb(0 0 0 / 8%);
}
/* Внутренняя тень дополняет уже знакомое преобразование нажатой кнопки. */
button:active {
box-shadow: inset 0 2px 3px rgb(0 0 0 / 25%);
}
/* Фигура обрезает только своё содержимое, тень родительской карточки остаётся снаружи. */
.gallery figure {
position: relative;
overflow: hidden;
border-radius: 12px;
}
.gallery figcaption {
position: absolute;
inset: auto 0 0;
padding: 2.5rem 0.5rem 0.5rem;
}
/* Запасная однотонная подложка остаётся в прежнем правиле; градиент подключается условно. */
@supports (background-image: linear-gradient(black, white)) {
.gallery figcaption {
background-color: transparent;
background-image: linear-gradient(
to top,
rgb(57 35 19 / 95%) 0,
rgb(57 35 19 / 95%) calc(100% - 2rem),
rgb(57 35 19 / 0%) 100%
);
}
}
/* Лапа остаётся верхним слоем; подсветка — под ней, над однотонным фоном. */
@supports (background-image: radial-gradient(white, transparent)) {
.intro {
background-image:
url("../assets/paw.svg"),
radial-gradient(ellipse at 80% 20%, rgb(255 196 110 / 45%), rgb(255 196 110 / 0%) 65%);
background-size: 4rem, auto;
background-position: right 1rem bottom 1rem, center;
background-repeat: no-repeat;
}
}
}
css/shop.css
.shop { --paper: #fffaf3; }
.shop main { max-width: 76rem; }
.shop h1 { text-align: left; font-size: clamp(2.3rem, 5vw, 4rem); margin: .4em 0; }
.shop h2 { margin: .2em 0; }
.shop h3 { margin: .2em 0; line-height: 1.3; }
.shop button, .shop input, .shop select { font: inherit; }
.shop button { font-weight: 650; }
.shop button:disabled { opacity: .55; cursor: not-allowed; }
.shop :focus-visible { outline: 3px solid #287a86; outline-offset: 4px; }
.shop [hidden] { display: none !important; }
.shop-hero { display: grid; grid-template-columns: 1.4fr 1fr; gap: 2rem; align-items: center; padding: 2rem 3rem; border-radius: 24px; background: #f5e3cc; margin: 1rem 0 3rem; }
.shop-hero p { max-width: 34rem; }
.shop-hero figure { margin: 0; text-align: center; }
.shop-hero img { height: 310px; width: 100%; object-fit: contain; }
.shop-hero figcaption { font-size: .85rem; color: var(--text-muted); }
.eyebrow { text-transform: uppercase; letter-spacing: .13em; font-size: .75rem; font-weight: 750; color: var(--accent); }
.muted { color: var(--text-muted); font-size: .875rem; }
.shop-link { display: inline-block; color: var(--accent); font-weight: 700; padding: .6rem 0; }
.section-heading { display: flex; justify-content: space-between; gap: 1rem; align-items: center; margin-bottom: 1.5rem; }
.filters { display: flex; gap: .85rem; align-items: end; flex-wrap: wrap; border: 1px solid #e5d5c2; border-radius: 18px; background: #f7eee3; padding: 1.1rem; }
.shop label { display: grid; gap: .4rem; font-size: .875rem; }
.filters .search { flex: 1 1 15rem; }
.shop .check { display: flex; align-items: center; gap: .5rem; min-height: 44px; }
.shop input[type="checkbox"] { width: 1.15rem; height: 1.15rem; }
.shop .secondary { background: transparent; color: var(--accent); border: 1px solid #bca286; }
.shop .secondary:hover { background: #f2dfc9; }
/* Поля и переключатели фильтра сохраняют нативное управление с клавиатуры. */
.filters > label:not(.check) { color: #715744; font-size: .75rem; font-weight: 650; gap: .5rem; }
.filters input[type="search"], .filters select { height: 46px; border: 1px solid #d7c4ae; border-radius: 11px; background-color: #fffdf9; color: var(--text); font-size: .875rem; font-weight: 400; box-shadow: 0 2px 3px #593b2010; }
.filters input[type="search"] { width: 100%; padding-left: 2.6rem; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' fill='none' stroke='%238b6c52' stroke-width='1.7' stroke-linecap='round'%3E%3Ccircle cx='8.5' cy='8.5' r='5.5'/%3E%3Cpath d='m13 13 4 4'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: .85rem center; }
.filters select { appearance: none; padding: 0 2.4rem 0 .85rem; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' stroke='%238b6c52' stroke-width='1.7' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 6 4 4 4-4'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right .8rem center; }
.filters input[type="search"]::placeholder { color: #8a7767; }
.filters .check { position: relative; height: 46px; padding: 0 .85rem; gap: .55rem; border: 1px solid #d7c4ae; border-radius: 11px; background: #fffdf9; color: #715744; cursor: pointer; font-size: .8125rem; white-space: nowrap; }
.filters .check:hover { border-color: #a57a52; }
.filters .check:has(:checked) { background: #efe0cd; border-color: #a57a52; color: #713c18; }
.filters .check input { appearance: none; flex-shrink: 0; width: 18px; height: 18px; margin: 0; border: 1.5px solid #b39b81; border-radius: 5px; background: white; }
.filters .check input:checked { border-color: var(--accent); background: var(--accent) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 9 3 3 7-7'/%3E%3C/svg%3E") center / 16px; }
.filters button[type="reset"] { min-height: 46px; padding: .5rem .65rem; border-color: transparent; border-radius: 10px; font-size: .8125rem; font-weight: 600; color: #715744; }
@media (forced-colors: active) { .filters .check input { appearance: auto; } .filters select { appearance: auto; } }
.products { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1.4rem; }
.product { border-radius: 16px; background: var(--paper); overflow: hidden; border: 1px solid #e2d2c0; display: flex; flex-direction: column; }
.product-art { position: relative; background: #efe2cf; }
.product:nth-child(3n + 2) .product-art { background: #e5e8dc; }
.product:nth-child(3n) .product-art { background: #efe0d8; }
.product-art img { width: 100%; height: 220px; object-fit: contain; padding: 1rem; display: block; }
.product .favorite { position: absolute; top: .8rem; right: .8rem; width: 44px; height: 44px; padding: 0; background: var(--paper); font-size: 1.4rem; }
.product-body { padding: 1.2rem; display: flex; flex: 1; flex-direction: column; }
.product-body p { margin: .3rem 0 .7rem; }
.product-description { font-size: .9rem; }
.product h3 a { color: inherit; text-decoration: none; }
.product h3 a:hover { text-decoration: underline; text-underline-offset: .2em; }
#product-page > a { color: var(--accent); text-underline-offset: .25em; }
.product-detail { display: grid; grid-template-columns: 1.1fr 1fr; gap: 2.5rem; align-items: start; margin-top: 2rem; }
.detail-gallery { min-width: 0; }
.shop .gallery-zoom { display: block; width: 100%; padding: 1.5rem; border-radius: 20px; background: #efe2cf; cursor: zoom-in; }
.gallery-zoom img { display: block; width: 100%; height: auto; }
.detail-price { font-size: 2rem; font-weight: 750; }
.detail-actions { display: flex; flex-wrap: wrap; gap: .75rem; }
.detail-gallery dialog img { display: block; width: 100%; }
@media (max-width: 650px) { .product-detail { grid-template-columns: 1fr; gap: 1rem; } }
.product-bottom { display: flex; gap: .5rem; justify-content: space-between; align-items: center; margin-top: auto; }
.price { white-space: nowrap; font-size: 1.15rem; }
.product-bottom button { padding: .5rem .9rem; font-size: .85rem; }
.shop-note { margin-top: 3rem; padding: 2rem; border-block: 1px solid #d9c5af; }
.shop-note p { max-width: 45rem; }
.shop dialog { width: min(40rem, calc(100% - 1.5rem)); max-height: 90dvh; padding: 1.5rem; border: 1px solid #d9c5af; border-radius: 20px; background: var(--paper); color: var(--text); }
.shop dialog::backdrop { background: rgb(43 33 27 / 55%); }
.shop:has(dialog[open]) { overflow: hidden; }
.cart-row { display: grid; grid-template-columns: 1fr auto; gap: .5rem; padding: 1rem 0; border-bottom: 1px solid #d9c5af; }
.quantity { display: flex; gap: .6rem; align-items: center; }
.quantity button { min-width: 44px; min-height: 44px; padding: .3rem; }
.cart-row .remove { font-size: .8rem; padding: .4rem .7rem; }
.promo { display: flex; gap: .75rem; align-items: end; margin-top: 1.5rem; }
.promo label { min-width: 0; flex: 1; }
.totals div { display: flex; justify-content: space-between; gap: 1rem; margin: .5rem 0; }
.totals dd { margin: 0; }
.grand-total { font-weight: 750; font-size: 1.3rem; border-top: 1px solid #d9c5af; padding-top: .6rem; }
#order-form { display: grid; gap: .8rem; border-top: 1px solid #d9c5af; padding-top: 1rem; }
#order-form p { margin: 0; }
#clear-cart { margin-top: 1rem; }
.error { color: #a02222; }
.notice:not(:empty), .storage-warning:not(:empty) { position: fixed; bottom: 1rem; left: 50%; transform: translateX(-50%); z-index: 20; margin: 0; padding: .8rem 1.2rem; width: max-content; max-width: 90%; background: #2b211b; color: white; border-radius: 12px; box-shadow: 0 4px 20px #0002; }
.storage-warning:not(:empty) { bottom: 5rem; }
.skip { position: absolute; left: -9999px; }
.skip:focus { left: 1rem; top: 1rem; z-index: 30; background: white; padding: 1rem; }
@media (max-width: 850px) { .products { grid-template-columns: repeat(2, minmax(0, 1fr)); } .shop-hero { padding: 1.5rem; gap: 1rem; } }
@media (max-width: 540px) { .shop-hero { grid-template-columns: 1fr; } .shop-hero img { height: 220px; } .products { grid-template-columns: 1fr; } .filters > label { flex: 1 1 100%; } .section-heading { flex-wrap: wrap; } .cart-row { grid-template-columns: 1fr; } .shop dialog { padding: 1rem; } }
/* Цвет иллюстрации сохраняется, когда поиск меняет порядок карточек. */
.products [data-id="ball"] .product-art { background-color: #e5e8dc; }
.products [data-id="rope"] .product-art { background-color: #efe2cf; }
.products [data-id="duck"] .product-art { background-color: #efe0d8; }
Подсказки на полях показывают, где писать код. Нажмите «?», чтобы перейти к первой подсказке. Нажмите ещё раз, чтобы скрыть их все.
Нажмите «Запустить», чтобы увидеть результат.
js/shop.js
/*
Лавка Тони: программа магазина.
Разделы: товары, заказ, проверки и чек.
*/
console.log("Лавка Тони");
// Товары
const productName = "Мяч для прогулок";
const price = 450;
const isAvailable = true;
const isFavorite = false;
const description = "";
const ropeName = "Канат «Удав»";
const ropePrice = 490;
const ropeStock = 8;
// Заказ
const quantityText = "3";
const quantity = Number(quantityText);
const selectedProduct = null;
const promoCode = null;
let pickupPoint;
const pickupCost = 0;
const deliveryText = "150";
const savedDelivery = 0;
const delivery = savedDelivery ?? Number(deliveryText);
const savedName = "";
const customerName = savedName || "Гость";
const paid = 2000;
const hasCard = false;
const hasCash = true;
const isBlocked = false;
const isPaid = true;
const payOnPickup = true;
// Склад
const incoming = 5;
const packSize = 4;
let stock = 12;
stock += incoming;
stock -= quantity;
stock++;
const unpacked = stock % packSize;
// Чек заказа
function calcTotal(itemPrice, itemQuantity, itemDelivery = 150) {
if (itemQuantity <= 0) {
return 0;
}
return itemPrice * itemQuantity + itemDelivery;
}
const subtotal = price * quantity;
const total = calcTotal(price, quantity, delivery);
const change = paid - total;
function printReceipt() {
console.log(`Товары: ${subtotal}`);
console.log(`К оплате: ${total}`);
console.log(`Сдача: ${change}`);
}
console.log("Чек покупателю");
printReceipt();
console.log("Копия для склада");
printReceipt();
// Проверки заказа
const freeDeliveryFrom = 1000;
const selectedName = "Мяч для прогулок";
const hasEnough = stock >= quantity;
const hasFreeDelivery = subtotal >= freeDeliveryFrom;
const sameName = selectedName === productName;
const validQuantity = quantity > 0 && quantity <= stock;
const canPay = hasCard || hasCash;
const canOrder = validQuantity && canPay && !isBlocked;
let message = "";
if (isBlocked) {
message = "Заказ недоступен";
} else if (!hasEnough) {
message = "Недостаточно товара";
} else if (isPaid) {
message = "Передаём заказ в доставку";
} else {
message = "Ожидаем оплату";
}
// Подписи
const productCode = "B17";
const card = `${productName} — ${price} руб.`;
const badge = productName[0] + "-" + productCode;
// Признаки товара
const hasDescription = Boolean(description);
// Скидка на каждый мяч
const discountPerItem = 50;
const discountedTotal = (price - discountPerItem) * quantity + delivery;
const canCheckout = hasEnough && (isPaid || payOnPickup);
// Способ получения и наличие
const isPickup = delivery === 0;
const methodLabel = "Способ: " + (isPickup ? "Самовывоз" : "Доставка");
const stockLabel = isAvailable ? "В наличии" : "Закончился";
// Способ получения по коду из формы
const methodText = "1";
const methodCode = Number(methodText);
let methodName = "";
let methodCost = null;
switch (methodCode) {
case 1:
methodName = "Самовывоз";
methodCost = 0;
break;
case 2:
case 3:
methodName = "Доставка";
methodCost = 150;
break;
default:
methodName = "Неизвестный способ";
methodCost = null;
break;
}
// Упаковка заказа
const boxCapacity = 2;
let remaining = quantity;
let boxes = 0;
while (remaining > 0) {
if (remaining > boxCapacity) {
remaining -= boxCapacity;
} else {
remaining = 0;
}
boxes++;
}
// Подарки к заказам: Тони дарит мячик каждому чётному заказу дня
const lastOrder = 10;
const giftsEndAt = 8;
let giftCount = 0;
let giftSum = 0;
for (let orderNumber = 1; orderNumber <= lastOrder; orderNumber++) {
if (orderNumber === giftsEndAt) {
break;
}
if (orderNumber % 2 !== 0) {
continue;
}
giftSum += orderNumber;
giftCount++;
}
// Проверка calcTotal
console.log(calcTotal(ropePrice, 2));
console.log(calcTotal(price, 2, 0));
console.log(calcTotal(price, 0, 150));
// Данные первого товара
const ball = {
id: "ball",
name: productName,
price: price,
stock: stock,
priceLabel() {
return this.price + " ₽";
}
};
console.log(ball.priceLabel());
const rope = { id: "rope", name: ropeName, price: ropePrice, stock: ropeStock };
const ring = { id: "ring", name: "Кольцо «Апорт»", price: 450, stock: 0 };
const catalog = [ball, rope, ring];
console.log(catalog.length);
for (const product of catalog) {
console.log(product.name);
}
// Пробная цена для подарка
const gift = { id: rope.id, name: rope.name, price: rope.price };
gift.price = 0;
console.log(gift.price, rope.price);
function offerPrice(product) {
return product.offer?.price ?? product.price;
}
console.log(offerPrice(rope));
console.log(offerPrice({ price: rope.price, offer: { price: 0 } }));
function availableProducts(products) {
return products.filter(product => product.stock > 0);
}
console.log(availableProducts(catalog).map(product => product.name));
function findProduct(id) {
return catalog.find(product => product.id === id);
}
console.log(findProduct("rope")?.name ?? "Товар не найден");
console.log(findProduct("cat")?.name ?? "Товар не найден");
function countStock(products) {
return products.reduce((sum, product) => sum + product.stock, 0);
}
console.log(countStock(catalog));
const cartDialog = document.querySelector("#cart-dialog");
const openCart = document.querySelector("#open-cart");
const closeCart = document.querySelector("#close-cart");
openCart.addEventListener("click", () => cartDialog.showModal());
closeCart.addEventListener("click", () => cartDialog.close());
cartDialog.addEventListener("close", () => openCart.focus());
document.querySelector(".product h3").textContent = ball.name;
document.querySelector(".product .price").textContent = ball.priceLabel();
const cart = [];
const cartCount = document.querySelector("#cart-count");
cartCount.textContent = cart.length;
const cartItems = document.querySelector("#cart-items");
function addBall() {
cart.push(ball.id);
cartCount.textContent = cart.length;
cartItems.textContent = findProduct(cart[cart.length - 1]).name + " × " + cart.length;
}
document.querySelector(".product .add").addEventListener("click", addBall);
index.html
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Лавка Тони — учебный магазин игрушек и вещей для собак.">
<title>Лавка Тони</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/shop.css">
</head>
<body class="shop">
<a class="skip" href="#catalog">К товарам</a>
<main>
<section class="shop-hero" aria-labelledby="shop-title">
<div><p class="eyebrow">Маленькая лавка большого друга</p><h1 id="shop-title">Для игр, прогулок<br>и сладких снов.</h1>
<p>Привет, это Тони! Готовлю лавку игрушек и вещей для наших собачьих дел.</p>
<a class="shop-link" href="#catalog">Заглянуть в лавку ↓</a><p class="muted">Учебный магазин · без оплаты и настоящих заказов</p></div>
<figure><img src="assets/tony-toy.png" alt="Тони со своим любимым канатом" width="300" height="400"><figcaption>Главный по проверке игрушек</figcaption></figure>
</section>
<section id="catalog" aria-labelledby="catalog-title">
<div class="section-heading"><div><p class="eyebrow">Выбрано с лапой</p><h2 id="catalog-title">Лавка Тони</h2></div>
<button id="open-cart" type="button">Корзина · <span id="cart-count">0</span></button>
</div>
<p id="catalog-status" role="status">Первый товар в Лавке.</p>
<div id="products" class="products">
<article class="product" data-id="ball">
<div class="product-art"><img src="assets/ball.svg" alt="Мяч для прогулок" width="300" height="240"></div>
<div class="product-body">
<h3></h3>
<div class="product-bottom"><strong class="price"></strong>
<button class="add" type="button">В корзину</button>
</div>
</div>
</article>
</div>
</section>
</main>
<footer><p>© 2026 Тони и его хозяин · Сделано для любопытных</p></footer>
<dialog id="cart-dialog" aria-labelledby="cart-title">
<div class="section-heading">
<h2 id="cart-title">Твоя корзина</h2>
<button id="close-cart" type="button" class="secondary">Закрыть</button>
</div>
<div id="cart-items">В корзине пока пусто. Тони советует начать с игрушки.</div>
</dialog>
<script src="js/shop.js"></script>
</body>
</html>
css/style.css
/* Все обычные правила проекта распределены по слоям. */
@layer base, layout, components;
@layer base {
/* Общие стили сайта Тони */
/* Ширина и высота включают внутренние отступы и рамку — у всех элементов и псевдоэлементов */
*,
*::before,
*::after {
box-sizing: border-box;
}
/* Палитра сайта в пользовательских свойствах: цвет меняется в одном месте */
:root {
--accent: saddlebrown; /* заголовки, меню, акценты */
--text: #2b211b; /* основной текст */
--text-muted: #6b5d52; /* подписи и второстепенный текст */
}
/* Шрифт заголовков Nunito (лицензия SIL Open Font License): кириллица и латиница в разных файлах */
@font-face {
font-family: "Nunito";
src: url("../assets/nunito-cyrillic-800-normal.woff2") format("woff2");
font-weight: 800;
font-display: swap; /* пока шрифт загружается, текст виден запасным шрифтом */
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
@font-face {
font-family: "Nunito";
src: url("../assets/nunito-latin-800-normal.woff2") format("woff2");
font-weight: 800;
font-display: swap;
unicode-range: U+0000-00FF, U+2000-206F, U+20AC, U+2122;
}
body {
background-color: linen;
color: var(--text); /* цвет для потомков без собственного значения */
font-size: 1.0625rem; /* 17px при настройке браузера по умолчанию */
font-family:
system-ui,
-apple-system,
"Segoe UI",
Roboto,
sans-serif; /* системный шрифт устройства */
line-height: 1.6; /* множитель: у каждого элемента интервал от его собственного размера шрифта */
margin: 0; /* убираем отступ браузера: шапка и подвал во всю ширину окна */
}
/* Поля основного содержимого: текст не прижимается к краям окна */
/* Изображения и видео не шире колонки, пропорции сохраняются */
img,
video {
max-width: 100%;
height: auto;
}
/* Фреймы, аудиоплеер и поля формы не выходят за колонку */
iframe,
audio,
input,
select,
textarea,
button {
max-width: 100%;
}
/* Разрешаем группе полей сужаться вместе с колонкой. */
fieldset {
min-width: 0;
}
/* Общий цвет заголовков — групповой селектор */
h1,
h2 {
color: var(--accent);
font-family: "Nunito", "Trebuchet MS", system-ui, sans-serif;
font-weight: 800;
line-height: 1.2; /* крупному тексту хватает меньшего интервала */
}
/* Размеры заголовков в rem — от размера шрифта корня, а не родителя */
h1 {
text-align: center;
font-size: 2.5rem;
}
h2 {
font-size: 1.75rem;
}
}
@layer layout {
main {
padding: 1.5rem 1rem;
max-width: 68rem; /* на широком экране строки не растягиваются на всё окно */
margin: 0 auto; /* колонка по центру */
}
}
@layer components {
/* Вводный блок главной страницы */
.intro {
background-color: hsl(30, 80%, 95%);
padding: 1.5rem; /* фон вокруг текста; заодно не выпускает margin заголовка за пределы блока */
border-radius: 16px; /* скругляется и фон, хотя рамки нет */
/* Лапка в правом нижнем углу; цвет фона выше остаётся запасным, если картинка не загрузится */
background-image: url("../assets/paw.svg");
background-repeat: no-repeat;
background-position: right 1rem bottom 1rem;
background-size: 4rem;
}
/* Разделы главной — светлые карточки на фоне страницы */
main > section {
background-color: var(--paper, #fffaf3);
border: 1px solid hsl(28, 30%, 82%);
border-radius: 16px;
padding: 1.5rem;
margin-top: 1.5rem;
}
/* Ширина вводных абзацев ограничена 60ch; количество букв в строке зависит от шрифта и текста */
.intro p {
max-width: 60ch;
}
/* Важное предупреждение во вводном блоке — темнее основного акцента */
.intro strong {
color: #6e3510;
}
/* Оглавление главной страницы — переносимый ряд «таблеток» на Flexbox */
.toc {
background-color: white;
border: 1px solid tan;
display: flex;
flex-wrap: wrap; /* «таблетки», которым не хватает места, переходят на новую строку */
gap: 0.5rem; /* промежутки между «таблетками» и между строками */
list-style: none;
padding: 0.75rem;
}
/* Подчёркивание ссылок чуть ниже букв: не задевает выносные элементы */
a {
text-underline-offset: 3px;
}
/* Тонкая линия отделяет шапку от страницы */
header {
border-bottom: 1px solid tan;
}
/* Меню в одну строку на Flexbox: пункты — флекс-элементы, промежутки задаёт gap */
nav ul {
margin: 0;
padding: 0.5rem 1rem;
display: flex;
gap: 0.5rem;
list-style: none;
}
/* Ссылка на запись стоит отдельно у правого края: автоматический отступ забирает свободное место */
nav li:last-child {
margin-left: auto;
}
/* Ссылки меню в шапке — селектор потомков */
nav a {
color: var(--accent);
text-decoration: none;
display: inline-block; /* у строчной ссылки вертикальный padding не раздвигает строку */
padding: 0.4rem 0.9rem;
border-radius: 999px; /* «таблетка»: радиус больше половины высоты */
}
/* Ссылки оглавления главной страницы */
.toc a {
color: var(--text-muted); /* тёплый серый: контраст 6.34:1 на белом фоне оглавления */
display: block; /* ссылка заполняет «таблетку» целиком */
padding: 0.25rem 0.75rem;
border: 1px solid tan;
border-radius: 999px;
text-decoration: none;
}
/* Фотографии со скруглёнными углами */
figure img {
border-radius: 8px;
}
figcaption {
color: var(--text-muted); /* тёплый серый: контраст 5.64:1 на фоне linen */
font-size: 0.95rem;
}
footer {
background-color: hsl(30, 50%, 90%);
text-align: center;
padding: 1rem;
}
/* Ссылка в подвале берёт цвет текста подвала */
footer a {
color: inherit;
}
/* Поля формы получают шрифт страницы вместо шрифта браузера */
input,
select,
textarea,
button {
font: inherit;
}
/* Ссылки темнеют при наведении указателя */
a:hover {
color: #5c2d0c;
}
/* Ссылки меню подчёркиваются при наведении и фокусе с клавиатуры */
nav a:hover,
nav a:focus-visible {
text-decoration: underline;
}
/* Заметная рамка фокуса у ссылок, полей и кнопок при работе с клавиатуры */
:focus-visible {
outline: 3px solid #1f6feb;
outline-offset: 3px;
}
/* Цитата из книги — шрифтом с засечками и курсивом */
blockquote {
font-family: Georgia, "Times New Roman", serif;
font-style: italic;
border-left: 4px solid tan; /* черта слева выделяет цитату */
padding-left: 1rem;
}
/* Подпись под цитатой — у правого края */
blockquote + figcaption {
text-align: right;
}
/* Строки формы на Flexbox: подпись — колонка постоянной ширины, поле занимает остаток строки,
а на узком экране переносится под подпись */
fieldset p {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1rem;
}
fieldset p label {
flex: 0 0 12rem; /* не растёт и не сжимается, исходная ширина 12rem */
}
fieldset p input,
fieldset p select,
fieldset p textarea {
flex: 1 1 12rem; /* растёт и сжимается от исходной ширины 12rem */
min-width: 0; /* поле может стать уже своего автоматического минимума */
}
/* Фотоальбом на Grid. Все правила альбома собраны во вложенный блок: & — сам .gallery */
.gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
gap: 1rem;
list-style: none;
padding: 0;
/* Карточка — точка отсчёта для значка */
& li {
position: relative;
}
/* Карточка со значком выделена рамкой */
& li:has(.badge) {
outline: 3px solid tan;
outline-offset: 4px;
border-radius: 8px;
}
& figure {
margin: 0;
}
& img {
width: 100%; /* фото заполняет ширину своей ячейки */
}
}
/* Список команд на Grid: термин в первой колонке шириной по самому длинному термину, описание — во второй */
dl {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 0.5rem 1rem;
}
dt {
grid-column: 1;
font-weight: bold;
}
dd {
grid-column: 2;
overflow-wrap: anywhere; /* длинный перевод переносится внутри своей колонки */
margin: 0; /* браузерный отступ слева больше не нужен: колонку задаёт сетка */
}
/* Длинные слова и адреса переносятся, а не выходят за край узкого экрана */
body {
overflow-wrap: break-word;
}
/* Таблица режима дня на узком экране прокручивается в своей рамке, а не сжимается до нечитаемых колонок */
.table-wrap {
overflow-x: auto;
}
table {
width: 100%;
min-width: 28rem;
}
/* Подпись таблицы прокручивается вместе с ней: прижимаем её к началу, чтобы она была видна сразу */
caption {
text-align: left;
}
/* Широкий экран: в разделе «Моя любимая игрушка» фото справа, текст слева.
На узком экране правило не действует, и раздел остаётся одной колонкой. */
@media (width >= 48rem) {
.toy {
display: grid;
grid-template-columns: minmax(0, 1fr) 300px;
column-gap: 1.5rem;
}
.toy figure {
grid-column: 2;
grid-row: 1 / span 6; /* фото рядом со всеми абзацами раздела */
margin: 0;
}
.toy hr {
width: 100%;
}
}
/* Значок «Любимая» в правом верхнем углу карточки; из потока исключён, поэтому фото не сдвигается */
.badge {
position: absolute;
top: 0.5rem;
right: 0.5rem;
padding: 0.2rem 0.7rem;
border-radius: 999px;
background-color: var(--accent);
color: white;
font-size: 0.85rem;
font-weight: bold;
}
/* Шапка прилипает к верхнему краю окна. Фон нужен, чтобы под шапкой не просвечивал текст страницы */
header {
position: sticky;
top: 0;
z-index: 10; /* выше карточек альбома: они тоже позиционированы и записаны в HTML позже шапки */
background-color: linen;
}
/* Липкая шапка должна быть низкой: пункты меню не сжимаются и не переносятся на вторую строку,
а если им не хватает места, меню прокручивается внутри шапки */
nav ul {
overflow-x: auto;
}
nav li {
flex-shrink: 0;
}
/* Заголовок, к которому ведёт ссылка-якорь, не прячется под липкой шапкой.
В rem: при увеличении текста растут и шапка, и отступ */
[id] {
scroll-margin-top: 4.5rem;
}
/* Ссылка, которая открывается в новой вкладке, помечена стрелкой — посетитель знает, что страница не сменится */
a[target="_blank"]::after {
content: " ↗";
}
/* Ссылка на электронную почту — с конвертом */
a[href^="mailto:"]::before {
content: "✉ ";
}
/* Первая ссылка меню — «Главная» — подписана лапкой без изменения HTML */
nav li:first-child a::before {
content: "🐾 ";
}
/* Первый абзац вводного блока крупнее остальных. :first-child здесь не подойдёт — первым стоит заголовок h1 */
.intro p:first-of-type {
font-size: 1.2rem;
}
/* Список игрушек: вместо стандартного кружка — косточка */
.toy-list li::marker {
content: "🦴 ";
}
/* Номера шагов в нумерованных списках — в цвет заголовков и жирные; текст пунктов не меняется */
ol li::marker {
color: var(--accent);
font-weight: bold;
}
/* Таблица режима дня: соседние рамки объединяются в одну линию */
table {
border-collapse: collapse;
}
/* Ячейки с воздухом и линией снизу; текст — от левого края и сверху, даже если в соседней ячейке две строки */
th,
td {
padding: 0.6rem 0.8rem;
border-bottom: 1px solid tan;
text-align: left;
vertical-align: top;
}
/* Шапка таблицы — в цвет заголовков сайта */
thead th {
background-color: var(--accent);
color: white;
}
/* Чётные строки тела таблицы — на светлом фоне: глаз не теряет строку */
tbody tr:nth-child(even) {
background-color: hsl(30, 80%, 95%);
}
/* Отдельные рамки без промежутков позволяют скруглить крайние ячейки. Линия только снизу не удваивается. */
table {
border-collapse: separate;
border-spacing: 0;
}
thead th:first-child {
border-top-left-radius: 8px;
}
thead th:last-child {
border-top-right-radius: 8px;
}
/* Форма записи: текстовые поля, список и область текста в едином стиле */
input:not([type="radio"], [type="checkbox"]),
select,
textarea {
padding: 0.5rem 0.75rem;
border: 1px solid #8a7660;
border-radius: 8px;
background-color: white;
}
/* Поле «Ведёт прогулку» менять нельзя — фон показывает это */
input[readonly] {
background-color: hsl(30, 80%, 95%);
}
/* Отмеченные флажки и переключатели — в цвет сайта */
input[type="radio"],
input[type="checkbox"] {
accent-color: var(--accent);
}
/* Неверно заполненное поле — после того как посетитель с ним поработал */
input:user-invalid,
select:user-invalid,
textarea:user-invalid {
border-color: firebrick;
}
/* Группы полей — светлые блоки с тонкой рамкой вместо рельефной рамки браузера */
fieldset {
margin-bottom: 1rem;
border: 1px solid #8a7660;
border-radius: 16px;
}
/* Группа полей, в которой сейчас работает посетитель */
fieldset:focus-within {
border-color: var(--accent);
}
/* Кнопки-«таблетки»: основная залита цветом, второстепенная — только рамка */
button {
padding: 0.7rem 1.4rem;
border: 2px solid var(--accent);
border-radius: 999px;
background-color: var(--accent);
color: white;
font-weight: bold;
cursor: pointer;
}
button[type="reset"] {
background-color: transparent;
color: var(--accent);
}
/* Текст ошибок связан с полями через aria-describedby и не полагается только на цвет рамки. */
.field-error {
display: none;
flex-basis: 100%;
color: firebrick;
font-weight: bold;
}
input:user-invalid + .field-error {
display: block;
}
/* Фото любимой игрушки — как карточка-полароид: слегка повёрнуто вокруг нижнего края, будто прижато к столу */
.toy img {
transform: rotate(-2deg);
transform-origin: 50% 100%;
}
/* Под указателем фото выпрямляется и чуть увеличивается */
.toy img:hover {
transform: rotate(0deg) scale(1.03);
}
/* «Таблетка» оглавления под указателем и в фокусе приподнимается: отдельное свойство translate */
.toc a:hover,
.toc a:focus-visible {
translate: 0 -2px;
}
/* Нажатая кнопка будто вдавливается */
button:active {
transform: translateY(1px) scale(0.98);
}
/* Плавные изменения: переходим конкретные свойства, а не all */
.toy img {
transition: transform 0.4s ease-out; /* фото выпрямляется плавно */
}
.toc a {
transition: translate 0.2s ease-out;
}
button {
transition:
background-color 0.2s,
transform 0.1s;
}
/* Посетитель попросил систему уменьшить движение — изменения происходят сразу, без переходов */
@media (prefers-reduced-motion: reduce) {
.toy img,
.toc a,
button {
transition: none;
}
}
/* Лапка у «Главной» машет, когда на ссылку наводят указатель */
@keyframes wag {
0%,
100% {
rotate: 0deg;
}
25% {
rotate: -18deg;
}
75% {
rotate: 18deg;
}
}
nav li:first-child a::before {
display: inline-block; /* строчный псевдоэлемент не поворачивается */
transform-origin: 50% 80%; /* лапка качается от «запястья» */
}
nav li:first-child a:hover::before,
nav li:first-child a:focus-visible::before {
animation-name: wag;
animation-duration: 0.5s;
animation-timing-function: ease-in-out;
animation-iteration-count: 2; /* помахать дважды и остановиться */
}
/* Приветствие на главной плавно появляется снизу при загрузке страницы */
@keyframes rise {
from {
opacity: 0;
translate: 0 16px;
}
/* to не задан: конечный кадр — обычный вид элемента */
}
.intro > * {
/* both: до старта — первый кадр (элемент скрыт во время задержки), после — последний */
animation: rise 0.6s ease-out both;
}
/* Строки появляются друг за другом */
.intro > :nth-child(2) {
animation-delay: 0.1s;
}
.intro > :nth-child(3) {
animation-delay: 0.2s;
}
.intro > :nth-child(4) {
animation-delay: 0.3s;
}
/* Посетитель попросил уменьшить движение — анимаций нет, всё видно сразу */
@media (prefers-reduced-motion: reduce) {
.intro > *,
nav li:first-child a:hover::before,
nav li:first-child a:focus-visible::before {
animation: none;
}
}
button:hover,
button:focus-visible {
background-color: #6b3513;
}
button[type="reset"]:hover,
button[type="reset"]:focus-visible {
background-color: hsl(30, 70%, 90%);
}
/* Подписи читаются на тёмной подложке и без декоративной тени. */
.gallery figcaption {
padding: 0.5rem;
color: white;
background-color: hsl(25, 50%, 15%);
text-shadow: 0 1px 3px rgb(0 0 0 / 60%);
}
/* Два слоя: чёткая тень у края и широкая мягкая тень под карточкой. */
.gallery li {
background-color: #fffaf3;
border-radius: 12px;
box-shadow: 0 1px 2px rgb(0 0 0 / 8%), 0 8px 24px rgb(0 0 0 / 8%);
}
/* Внутренняя тень дополняет уже знакомое преобразование нажатой кнопки. */
button:active {
box-shadow: inset 0 2px 3px rgb(0 0 0 / 25%);
}
/* Фигура обрезает только своё содержимое, тень родительской карточки остаётся снаружи. */
.gallery figure {
position: relative;
overflow: hidden;
border-radius: 12px;
}
.gallery figcaption {
position: absolute;
inset: auto 0 0;
padding: 2.5rem 0.5rem 0.5rem;
}
/* Запасная однотонная подложка остаётся в прежнем правиле; градиент подключается условно. */
@supports (background-image: linear-gradient(black, white)) {
.gallery figcaption {
background-color: transparent;
background-image: linear-gradient(
to top,
rgb(57 35 19 / 95%) 0,
rgb(57 35 19 / 95%) calc(100% - 2rem),
rgb(57 35 19 / 0%) 100%
);
}
}
/* Лапа остаётся верхним слоем; подсветка — под ней, над однотонным фоном. */
@supports (background-image: radial-gradient(white, transparent)) {
.intro {
background-image:
url("../assets/paw.svg"),
radial-gradient(ellipse at 80% 20%, rgb(255 196 110 / 45%), rgb(255 196 110 / 0%) 65%);
background-size: 4rem, auto;
background-position: right 1rem bottom 1rem, center;
background-repeat: no-repeat;
}
}
}
css/shop.css
.shop { --paper: #fffaf3; }
.shop main { max-width: 76rem; }
.shop h1 { text-align: left; font-size: clamp(2.3rem, 5vw, 4rem); margin: .4em 0; }
.shop h2 { margin: .2em 0; }
.shop h3 { margin: .2em 0; line-height: 1.3; }
.shop button, .shop input, .shop select { font: inherit; }
.shop button { font-weight: 650; }
.shop button:disabled { opacity: .55; cursor: not-allowed; }
.shop :focus-visible { outline: 3px solid #287a86; outline-offset: 4px; }
.shop [hidden] { display: none !important; }
.shop-hero { display: grid; grid-template-columns: 1.4fr 1fr; gap: 2rem; align-items: center; padding: 2rem 3rem; border-radius: 24px; background: #f5e3cc; margin: 1rem 0 3rem; }
.shop-hero p { max-width: 34rem; }
.shop-hero figure { margin: 0; text-align: center; }
.shop-hero img { height: 310px; width: 100%; object-fit: contain; }
.shop-hero figcaption { font-size: .85rem; color: var(--text-muted); }
.eyebrow { text-transform: uppercase; letter-spacing: .13em; font-size: .75rem; font-weight: 750; color: var(--accent); }
.muted { color: var(--text-muted); font-size: .875rem; }
.shop-link { display: inline-block; color: var(--accent); font-weight: 700; padding: .6rem 0; }
.section-heading { display: flex; justify-content: space-between; gap: 1rem; align-items: center; margin-bottom: 1.5rem; }
.filters { display: flex; gap: .85rem; align-items: end; flex-wrap: wrap; border: 1px solid #e5d5c2; border-radius: 18px; background: #f7eee3; padding: 1.1rem; }
.shop label { display: grid; gap: .4rem; font-size: .875rem; }
.filters .search { flex: 1 1 15rem; }
.shop .check { display: flex; align-items: center; gap: .5rem; min-height: 44px; }
.shop input[type="checkbox"] { width: 1.15rem; height: 1.15rem; }
.shop .secondary { background: transparent; color: var(--accent); border: 1px solid #bca286; }
.shop .secondary:hover { background: #f2dfc9; }
/* Поля и переключатели фильтра сохраняют нативное управление с клавиатуры. */
.filters > label:not(.check) { color: #715744; font-size: .75rem; font-weight: 650; gap: .5rem; }
.filters input[type="search"], .filters select { height: 46px; border: 1px solid #d7c4ae; border-radius: 11px; background-color: #fffdf9; color: var(--text); font-size: .875rem; font-weight: 400; box-shadow: 0 2px 3px #593b2010; }
.filters input[type="search"] { width: 100%; padding-left: 2.6rem; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' fill='none' stroke='%238b6c52' stroke-width='1.7' stroke-linecap='round'%3E%3Ccircle cx='8.5' cy='8.5' r='5.5'/%3E%3Cpath d='m13 13 4 4'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: .85rem center; }
.filters select { appearance: none; padding: 0 2.4rem 0 .85rem; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='none' stroke='%238b6c52' stroke-width='1.7' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 6 4 4 4-4'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right .8rem center; }
.filters input[type="search"]::placeholder { color: #8a7767; }
.filters .check { position: relative; height: 46px; padding: 0 .85rem; gap: .55rem; border: 1px solid #d7c4ae; border-radius: 11px; background: #fffdf9; color: #715744; cursor: pointer; font-size: .8125rem; white-space: nowrap; }
.filters .check:hover { border-color: #a57a52; }
.filters .check:has(:checked) { background: #efe0cd; border-color: #a57a52; color: #713c18; }
.filters .check input { appearance: none; flex-shrink: 0; width: 18px; height: 18px; margin: 0; border: 1.5px solid #b39b81; border-radius: 5px; background: white; }
.filters .check input:checked { border-color: var(--accent); background: var(--accent) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 18 18' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m4 9 3 3 7-7'/%3E%3C/svg%3E") center / 16px; }
.filters button[type="reset"] { min-height: 46px; padding: .5rem .65rem; border-color: transparent; border-radius: 10px; font-size: .8125rem; font-weight: 600; color: #715744; }
@media (forced-colors: active) { .filters .check input { appearance: auto; } .filters select { appearance: auto; } }
.products { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1.4rem; }
.product { border-radius: 16px; background: var(--paper); overflow: hidden; border: 1px solid #e2d2c0; display: flex; flex-direction: column; }
.product-art { position: relative; background: #efe2cf; }
.product:nth-child(3n + 2) .product-art { background: #e5e8dc; }
.product:nth-child(3n) .product-art { background: #efe0d8; }
.product-art img { width: 100%; height: 220px; object-fit: contain; padding: 1rem; display: block; }
.product .favorite { position: absolute; top: .8rem; right: .8rem; width: 44px; height: 44px; padding: 0; background: var(--paper); font-size: 1.4rem; }
.product-body { padding: 1.2rem; display: flex; flex: 1; flex-direction: column; }
.product-body p { margin: .3rem 0 .7rem; }
.product-description { font-size: .9rem; }
.product h3 a { color: inherit; text-decoration: none; }
.product h3 a:hover { text-decoration: underline; text-underline-offset: .2em; }
#product-page > a { color: var(--accent); text-underline-offset: .25em; }
.product-detail { display: grid; grid-template-columns: 1.1fr 1fr; gap: 2.5rem; align-items: start; margin-top: 2rem; }
.detail-gallery { min-width: 0; }
.shop .gallery-zoom { display: block; width: 100%; padding: 1.5rem; border-radius: 20px; background: #efe2cf; cursor: zoom-in; }
.gallery-zoom img { display: block; width: 100%; height: auto; }
.detail-price { font-size: 2rem; font-weight: 750; }
.detail-actions { display: flex; flex-wrap: wrap; gap: .75rem; }
.detail-gallery dialog img { display: block; width: 100%; }
@media (max-width: 650px) { .product-detail { grid-template-columns: 1fr; gap: 1rem; } }
.product-bottom { display: flex; gap: .5rem; justify-content: space-between; align-items: center; margin-top: auto; }
.price { white-space: nowrap; font-size: 1.15rem; }
.product-bottom button { padding: .5rem .9rem; font-size: .85rem; }
.shop-note { margin-top: 3rem; padding: 2rem; border-block: 1px solid #d9c5af; }
.shop-note p { max-width: 45rem; }
.shop dialog { width: min(40rem, calc(100% - 1.5rem)); max-height: 90dvh; padding: 1.5rem; border: 1px solid #d9c5af; border-radius: 20px; background: var(--paper); color: var(--text); }
.shop dialog::backdrop { background: rgb(43 33 27 / 55%); }
.shop:has(dialog[open]) { overflow: hidden; }
.cart-row { display: grid; grid-template-columns: 1fr auto; gap: .5rem; padding: 1rem 0; border-bottom: 1px solid #d9c5af; }
.quantity { display: flex; gap: .6rem; align-items: center; }
.quantity button { min-width: 44px; min-height: 44px; padding: .3rem; }
.cart-row .remove { font-size: .8rem; padding: .4rem .7rem; }
.promo { display: flex; gap: .75rem; align-items: end; margin-top: 1.5rem; }
.promo label { min-width: 0; flex: 1; }
.totals div { display: flex; justify-content: space-between; gap: 1rem; margin: .5rem 0; }
.totals dd { margin: 0; }
.grand-total { font-weight: 750; font-size: 1.3rem; border-top: 1px solid #d9c5af; padding-top: .6rem; }
#order-form { display: grid; gap: .8rem; border-top: 1px solid #d9c5af; padding-top: 1rem; }
#order-form p { margin: 0; }
#clear-cart { margin-top: 1rem; }
.error { color: #a02222; }
.notice:not(:empty), .storage-warning:not(:empty) { position: fixed; bottom: 1rem; left: 50%; transform: translateX(-50%); z-index: 20; margin: 0; padding: .8rem 1.2rem; width: max-content; max-width: 90%; background: #2b211b; color: white; border-radius: 12px; box-shadow: 0 4px 20px #0002; }
.storage-warning:not(:empty) { bottom: 5rem; }
.skip { position: absolute; left: -9999px; }
.skip:focus { left: 1rem; top: 1rem; z-index: 30; background: white; padding: 1rem; }
@media (max-width: 850px) { .products { grid-template-columns: repeat(2, minmax(0, 1fr)); } .shop-hero { padding: 1.5rem; gap: 1rem; } }
@media (max-width: 540px) { .shop-hero { grid-template-columns: 1fr; } .shop-hero img { height: 220px; } .products { grid-template-columns: 1fr; } .filters > label { flex: 1 1 100%; } .section-heading { flex-wrap: wrap; } .cart-row { grid-template-columns: 1fr; } .shop dialog { padding: 1rem; } }
/* Цвет иллюстрации сохраняется, когда поиск меняет порядок карточек. */
.products [data-id="ball"] .product-art { background-color: #e5e8dc; }
.products [data-id="rope"] .product-art { background-color: #efe2cf; }
.products [data-id="duck"] .product-art { background-color: #efe0d8; }
- Файл с правками
- Добавлено
Точка на вкладке отмечает файл с правками. Зелёным выделены добавленные фрагменты кода.
Изменён файл js/shop.js
Добавленостроки 202–206
function countStock(products) {
return products.reduce((sum, product) => sum + product.stock, 0);
}
console.log(countStock(catalog));
Нажмите «Запустить», чтобы увидеть результат.
Задание. Сколько товара на складе
В catalog у каждого товара указаны цена за штуку и остаток. Выполните оба расчёта через
reduce(), начиная с 0.
- Вычислите общую стоимость всех товаров на складе с учётом количества каждого товара.
- Подсчитайте, сколько всего штук осталось на складе.
Ожидаемый результат. Первый вывод — 10670 рублей, второй — 23 штуки. Кольцо с нулевым
остатком ничего не прибавляет.
Обнулите остаток канатов. Их было восемь по 490 рублей, поэтому останутся 15 штук на 6750 рублей.
Проверьте в консоли
Условие задания
index.html
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Сколько товара на складе</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
script.js
const catalog = [
{ id: "ball", name: "Мяч для прогулок", price: 450, stock: 15 },
{ id: "rope", name: "Канат «Удав»", price: 490, stock: 8 },
{ id: "ring", name: "Кольцо «Апорт»", price: 450, stock: 0 }
];
const stockValue = catalog.reduce((sum, product) => sum + product.price);
const stockUnits = 0;
console.log(stockValue);
console.log(stockUnits);
Задание. Сколько вещей в корзине
В массиве cart каждая запись описывает выбранный товар. Свойство quantity хранит число
штук в позиции.
- Посчитайте общее число вещей в корзине сначала циклом, затем через
reduce. - Проверьте, что оба способа дают одинаковый итог и сохраняют исходный список.
Ожидаемый результат: два сообщения 3. Для пустого списка оба итога — 0, а для одной позиции с
двумя мячами — 2. Не записывайте готовый итог вместо расчёта.
Выполните задание
Условие задания
index.html
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Сколько вещей в корзине</title>
</head>
<body>
<h1>Сколько вещей в корзине</h1>
<script src="script.js"></script>
</body>
</html>
script.js
const cart = [{ id: "ball", quantity: 2 }, { id: "rope", quantity: 1 }];
// Вычислите итог двумя способами.
Подсказка
Начальное значение накопителя — число. Возвращаемое callback значение должно включать и прежнюю сумму, и количество вещей в очередной позиции.