Обработка нажатия
Чтение — около 10 минут· без учёта практики
В уроке
«Первая кнопка с JavaScript»
мы познакомились с событием click. Когда покупатель нажимал «Поздороваться», браузер вызывал функцию
sayHello и на странице появлялось приветствие Тони. Теперь на примере корзины разберём подробнее, когда
вызывается обработчик, как передать ему аргумент и где хранить количество товаров между нажатиями.
События
Браузер сообщает о действиях на странице через события. У каждого типа события есть имя, по которому скрипт может выбрать, на что реагировать. Вот лишь несколько событий, которые встречаются в Лавке.
click— покупатель нажал кнопку «Корзина» мышью или активировал её с клавиатуры.-
focus— поле поиска получило фокус, например когда покупатель перешёл к нему клавишей Tab. -
keydown— покупатель нажал клавишу, например стрелку влево, чтобы передвинуть курсор в поле поиска. input— покупатель изменил текст в поле поиска, например ввёл или вставил слово «мяч».submit— покупатель отправляет форму заказа. Это событие возникает у самой формы.
Чтобы выполнить код в ответ на событие, подключаем к элементу обработчик — функцию, которую браузер вызовет, когда это событие произойдёт.
Другие примеры, от прокрутки страницы до окончания видео, собраны в
справочнике HTML-атрибутов событий.
Например, в нём onclick — имя атрибута, который задаёт обработчик, а click — имя самого
события.
Выполняем код при нажатии
В шапке каталога Лавки Тони есть кнопка «Корзина · 0». По нажатию она открывает окно «Твоя корзина». В предыдущем уроке текст менялся при запуске программы, а теперь подождём, пока посетитель нажмёт кнопку.
Найдём кнопку через querySelector() и с помощью
addEventListener()
подключим функцию openCart к событию click.
Сначала подключите обработчик, затем нажмите кнопку
Запустите пример и посмотрите, какая строка появилась в панели «Консоль», пока корзина ещё закрыта. Теперь нажмите «Корзина · 0». Какую строку добавил обработчик, когда открылось окно? Нажмите «Закрыть» и откройте корзину ещё раз.
index.html
<main>
<h1>Лавка Тони</h1>
<button id="open-cart" type="button">Корзина · <span id="cart-count">0</span></button>
<dialog id="cart-dialog" aria-labelledby="cart-title">
<h2 id="cart-title">Твоя корзина</h2>
<button id="close-cart" type="button" class="secondary">Закрыть</button>
<p>В корзине пока пусто. Тони советует начать с игрушки.</p>
</dialog>
</main>
main.js
const button = document.querySelector("#open-cart");
const dialog = document.querySelector("#cart-dialog");
const closeButton = document.querySelector("#close-cart");
function openCart() {
if (dialog !== null) {
dialog.showModal();
console.log("Корзина открыта");
}
}
if (button !== null) {
button.addEventListener("click", openCart);
console.log("Обработчик подключён");
}
if (closeButton !== null && dialog !== null) {
closeButton.addEventListener("click", function () {
dialog.close();
console.log("Корзина закрыта");
});
}
style.css
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 16px;
background: #faf7f0;
color: #29251f;
font-family: system-ui, sans-serif;
line-height: 1.5;
overflow-wrap: anywhere;
}
main {
max-width: 640px;
margin: auto;
}
h1, h2, h3 {
line-height: 1.2;
}
.product, .cart {
margin-block: 12px;
padding: 16px;
border: 2px solid #b3a58c;
border-radius: 8px;
background: #fff;
}
.product h3 {
margin-top: 0;
}
.is-muted {
color: #665c4c;
border-style: dashed;
}
.is-selected, .is-ready {
border-color: #246341;
background: #edf7ef;
}
.is-unavailable .availability {
color: #9c2828;
font-weight: 700;
}
button {
max-width: 100%;
padding: .7rem 1.4rem;
border: 2px solid saddlebrown;
border-radius: 999px;
background: saddlebrown;
color: white;
font: inherit;
font-weight: 650;
cursor: pointer;
}
button:focus-visible {
outline: 3px solid #287a86;
outline-offset: 4px;
}
button + button {
margin-top: 8px;
}
Нажмите «Запустить», чтобы увидеть результат.
Вызов button.addEventListener("click", openCart) состоит из двух важных аргументов:
"click" — строковое имя события, openCart — сама функция. При подключении обработчика тело
openCart не выполняется, поэтому программа идёт дальше и выводит «Обработчик подключён».
В нашем примере document.querySelector("#cart-dialog") находит HTML-элемент
<dialog>. В переменной dialog хранится ссылка на этот элемент. У него уже есть встроенные методы
showModal() и close(), которые предоставляет браузер.
Когда покупатель нажимает «Корзина · 0», браузер вызывает openCart. Внутри неё
dialog.showModal() открывает корзину как модальное окно. Пока оно открыто, остальная часть страницы
недоступна для взаимодействия. При нажатии «Закрыть» обработчик этой кнопки вызывает dialog.close(), и
окно закрывается.
Функция и результат её вызова
Мы уже передавали callback-функции в методы массивов. Здесь тоже передаём функцию для вызова другим кодом, но момент вызова связан с событием. Скобки после имени меняют смысл записи. Отдельно рассмотрим ошибочный вариант:
// Вызываем сейчас и передаём результат вызова.
button.addEventListener("click", openCart());
В этой записи для нашей функции допущена ошибка: окно корзины откроется уже при запуске. У openCart() нет
return, поэтому результат — undefined. Это не функция, которую нужно вызвать при будущем
нажатии, и ожидаемый обработчик не подключится. Такой код не обязательно сообщит об ошибке в консоли: проверяйте и
момент появления результата, и реакцию на кнопку.
Имя события записывается без on: "click", а не "onclick". Имена чувствительны к
регистру: "Click" — другое имя. Для рассматриваемой кнопки браузер отправляет событие click.
Данные сохраняются между нажатиями
Теперь на каждое нажатие будем увеличивать количество мяча. Переменная quantity объявлена снаружи
обработчика, поэтому его вызовы работают с одним и тем же значением.
Добавьте несколько товаров
Нажмите «В корзину» дважды. Перед каждым нажатием предскажите количество и сумму. Затем поменяйте price на 200, перезапустите пример и проверьте свой расчёт.
index.html
<main>
<h1>Лавка Тони</h1>
<article class="product">
<h2>Мяч для прогулок</h2>
<p id="unit-price"></p>
<button id="add" type="button">В корзину</button>
</article>
<section class="cart" id="cart" aria-labelledby="cart-title">
<h2 id="cart-title">Корзина</h2>
<p id="summary" role="status">Товаров: 0, сумма: 0 ₽</p>
</section>
</main>
main.js
const button = document.querySelector("#add");
const summary = document.querySelector("#summary");
const unitPrice = document.querySelector("#unit-price");
const price = 450;
let quantity = 0;
if (unitPrice !== null) {
unitPrice.textContent = price + " ₽ за штуку";
}
function addProduct() {
quantity += 1;
if (summary !== null) {
summary.textContent = "Товаров: " + quantity + ", сумма: " + price * quantity + " ₽";
console.log(summary.textContent);
}
}
if (button !== null) {
button.addEventListener("click", addProduct);
}
style.css
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 16px;
background: #faf7f0;
color: #29251f;
font-family: system-ui, sans-serif;
line-height: 1.5;
overflow-wrap: anywhere;
}
main {
max-width: 640px;
margin: auto;
}
h1, h2, h3 {
line-height: 1.2;
}
.product, .cart {
margin-block: 12px;
padding: 16px;
border: 2px solid #b3a58c;
border-radius: 8px;
background: #fff;
}
.product h3 {
margin-top: 0;
}
.is-muted {
color: #665c4c;
border-style: dashed;
}
.is-selected, .is-ready {
border-color: #246341;
background: #edf7ef;
}
.is-unavailable .availability {
color: #9c2828;
font-weight: 700;
}
button {
max-width: 100%;
padding: .7rem 1.4rem;
border: 2px solid saddlebrown;
border-radius: 999px;
background: saddlebrown;
color: white;
font: inherit;
font-weight: 650;
cursor: pointer;
}
button:focus-visible {
outline: 3px solid #287a86;
outline-offset: 4px;
}
button + button {
margin-top: 8px;
}
Нажмите «Запустить», чтобы увидеть результат.
Порядок действий внутри обработчика важен: сначала меняем данные через quantity += 1, затем выводим новое
количество и рассчитанную сумму. Мы не читаем число из подписи кнопки или текста корзины: данные находятся в
переменной, а текст страницы показывает их текущее состояние.
Если поместить let quantity = 0 внутрь addProduct(), при каждом вызове будет создаваться
новое локальное значение ноль. После увеличения оно каждый раз станет единицей. Внешняя переменная нужна именно для
хранения количества между вызовами. Это хранение в памяти открытой страницы, не сохранение на диске или сервере.
Если обработчику нужны наши аргументы
Одна кнопка добавляет один мяч, другая — сразу два. Вынесем изменение количества в addProducts(amount).
Каждой кнопке передадим свою функцию-обёртку. Проследим, когда обёртка второй кнопки передаст число 2.
Отложите вызов с аргументом
Проверьте количество при запуске, затем нажмите «Добавить две штуки» и «В корзину». Замените addProducts(2) на addProducts(3), обновите подпись второй кнопки в HTML и сравните итоговую сумму.
index.html
<main>
<h1>Лавка Тони</h1>
<article class="product">
<h2>Мяч для прогулок</h2>
<p>450 ₽ за штуку</p>
<button id="add" type="button">В корзину</button>
<button id="add-two" type="button">Добавить две штуки</button>
</article>
<section class="cart" id="cart" aria-labelledby="cart-title">
<h2 id="cart-title">Корзина</h2>
<p id="summary" role="status">Товаров: 0, сумма: 0 ₽</p>
</section>
</main>
main.js
const oneButton = document.querySelector("#add");
const twoButton = document.querySelector("#add-two");
const summary = document.querySelector("#summary");
let quantity = 0;
function addProducts(amount) {
quantity += amount;
if (summary !== null) {
summary.textContent = "Товаров: " + quantity + ", сумма: " + 450 * quantity + " ₽";
console.log(summary.textContent);
}
}
if (oneButton !== null && twoButton !== null) {
oneButton.addEventListener("click", () => {
addProducts(1);
});
twoButton.addEventListener("click", () => {
addProducts(2);
});
}
style.css
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 16px;
background: #faf7f0;
color: #29251f;
font-family: system-ui, sans-serif;
line-height: 1.5;
overflow-wrap: anywhere;
}
main {
max-width: 640px;
margin: auto;
}
h1, h2, h3 {
line-height: 1.2;
}
.product, .cart {
margin-block: 12px;
padding: 16px;
border: 2px solid #b3a58c;
border-radius: 8px;
background: #fff;
}
.product h3 {
margin-top: 0;
}
.is-muted {
color: #665c4c;
border-style: dashed;
}
.is-selected, .is-ready {
border-color: #246341;
background: #edf7ef;
}
.is-unavailable .availability {
color: #9c2828;
font-weight: 700;
}
button {
max-width: 100%;
padding: .7rem 1.4rem;
border: 2px solid saddlebrown;
border-radius: 999px;
background: saddlebrown;
color: white;
font: inherit;
font-weight: 650;
cursor: pointer;
}
button:focus-visible {
outline: 3px solid #287a86;
outline-offset: 4px;
}
button + button {
margin-top: 8px;
}
Нажмите «Запустить», чтобы увидеть результат.
Стрелочная функция () => { addProducts(2); } создаётся при подключении. Её тело выполнится, когда
браузер вызовет обработчик, и только тогда произойдёт addProducts(2). Можно написать обычную функцию
вместо стрелочной — правило о передаче функции остаётся тем же.
twoButton.addEventListener("click", function () {
addProducts(2);
});
Браузер передаёт обработчику объект события, а не выбранное нами количество товаров. Поэтому простое
addEventListener("click", addProducts) не подставит в amount число 1 или 2. В этой статье
объект события нам не нужен, а его свойства разберём при подробном изучении событий.
Кнопка работает и с клавиатуры
Чтобы покупатель мог добавить мяч в корзину с клавиатуры, используем обычную кнопку
<button>. Клавиша Tab переводит на неё фокус. Рамка вокруг кнопки показывает, что сейчас её можно нажать клавишей
Enter или Пробел. Браузер вызовет тот же обработчик click, что и при нажатии мышью
или касании экрана.
Результат покажем в абзаце под кнопкой. Чтобы об обновлении мог узнать и тот, кто слушает страницу с помощью
скринридера (программы экранного доступа), добавим абзацу атрибут role="status". Он обозначает область
для сообщений. Когда обработчик изменит её текст, скринридер сможет прочитать новое количество мячей после текущей
реплики. Фокус останется на кнопке, поэтому покупатель сможет сразу добавить ещё один мяч.
Добавьте мяч с клавиатуры
Запустите пример. Нажимайте Tab, пока в области результата вокруг кнопки «Добавить мяч» не появится рамка. Нажмите Enter — под кнопкой появится «Мячей в корзине: 1». Затем нажмите Пробел — число увеличится до 2.
index.html
<button id="add-ball" type="button">Добавить мяч</button>
<p id="cart-status" role="status">Мячей в корзине: 0</p>
main.js
const addButton = document.querySelector('#add-ball')
const cartStatus = document.querySelector('#cart-status')
let quantity = 0
if (addButton !== null && cartStatus !== null) {
addButton.addEventListener('click', function () {
quantity += 1
cartStatus.textContent = 'Мячей в корзине: ' + quantity
})
}
Нажмите «Запустить», чтобы увидеть результат.
Внешний вид кнопки можно изменить через CSS, сохранив управление с клавиатуры. Атрибут
type="button"
пригодится, если позже мы поместим кнопку в форму. Нажатие по-прежнему добавит мяч без отправки формы.
Коротко
-
button.addEventListener("click", handler)— передавайте функцию без скобок, иначе она выполнится сразу. - Состояние, которое должно сохраняться между нажатиями, храните вне обработчика.
-
Если обработчику нужны свои аргументы, оберните вызов:
() => { addProducts(2); }. Обёртка создаётся сразу, аaddProducts(2)выполнится только при нажатии. - Элемент
<button>срабатывает и с клавиатуры, поэтому для действий используйте именно его. - После правки кода запустите пример снова. Редактор создаст новую страницу, и счётчик начнёт с нуля.
Проверьте себя
Выберите ответ — объяснение появится сразу. Ответ можно менять.
Задания
Задание. Проект «Лавка Тони» — остановите покупки при исчерпании запаса
Эти же шаги можно выполнить в своей папке.
-
В начале
addBall()сравнитеcart.lengthсball.stock. Если мячей уже столько, сколько есть на складе, или больше, завершите обработчик с помощьюreturn. -
Для проверки временно задайте
ball.stockзначение 2. Нажмите «В корзину» трижды и загляните в окно. Затем верните исходный остаток.
Проверьте результат. При запасе 2 третье нажатие оставляет «Мяч для прогулок × 2» и «Корзина · 2». При нулевом запасе корзина остаётся пустой.
Остановите покупки при исчерпании запаса
Условие задания
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));
function byPrice(products) {
return [...products].sort((first, second) => first.price - second.price);
}
console.log(byPrice(catalog).map(product => product.id));
console.log(catalog.map(product => product.id));
function searchProducts(products, query) {
const word = query.trim().toLowerCase();
return products.filter(product => product.name.toLowerCase().includes(word));
}
console.log(searchProducts(catalog, " КАНАТ ").map(product => product.name));
function checkEqual(label, actual, expected) {
if (actual === expected) {
console.log("Пройдено: " + label);
} else {
console.log("Ошибка: " + label, actual, expected);
}
}
checkEqual("пустой склад", countStock([]), 0);
checkEqual("поиск без регистра", searchProducts(catalog, " КаНаТ ")[0]?.id, "rope");
checkEqual("неизвестный код", findProduct("cat"), undefined);
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 cartItems = document.querySelector("#cart-items");
const cart = [];
const cartCount = document.querySelector("#cart-count");
function renderBallCart() {
cartCount.textContent = cart.length;
cartItems.textContent = cart.length ? findProduct(cart[cart.length - 1]).name + " × " + cart.length : "В корзине пока пусто. Тони советует начать с игрушки.";
}
function addBall() {
cart.push(ball.id);
renderBallCart();
}
document.querySelector(".product .add").addEventListener("click", addBall);
renderBallCart();
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));
function byPrice(products) {
return [...products].sort((first, second) => first.price - second.price);
}
console.log(byPrice(catalog).map(product => product.id));
console.log(catalog.map(product => product.id));
function searchProducts(products, query) {
const word = query.trim().toLowerCase();
return products.filter(product => product.name.toLowerCase().includes(word));
}
console.log(searchProducts(catalog, " КАНАТ ").map(product => product.name));
function checkEqual(label, actual, expected) {
if (actual === expected) {
console.log("Пройдено: " + label);
} else {
console.log("Ошибка: " + label, actual, expected);
}
}
checkEqual("пустой склад", countStock([]), 0);
checkEqual("поиск без регистра", searchProducts(catalog, " КаНаТ ")[0]?.id, "rope");
checkEqual("неизвестный код", findProduct("cat"), undefined);
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 cartItems = document.querySelector("#cart-items");
const cart = [];
const cartCount = document.querySelector("#cart-count");
function renderBallCart() {
cartCount.textContent = cart.length;
cartItems.textContent = cart.length ? findProduct(cart[cart.length - 1]).name + " × " + cart.length : "В корзине пока пусто. Тони советует начать с игрушки.";
}
function addBall() {
if (cart.length >= ball.stock) return;
cart.push(ball.id);
renderBallCart();
}
document.querySelector(".product .add").addEventListener("click", addBall);
renderBallCart();
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
Добавленострока 252
if (cart.length >= ball.stock) return;Нажмите «Запустить», чтобы увидеть результат.
Задание. Подключите кнопки корзины
В заготовке есть функции добавления и очистки корзины.
- Подключите каждую функцию к своей кнопке через
addEventListener. - Вызовите
renderCart, чтобы счётчик показал количество товаров сразу при открытии страницы.
Ожидаемый результат. При запуске появится «Корзина · 0». Два нажатия «В корзину» дадут 2, затем «Очистить корзину» вернёт 0.
Выполните задание
Условие задания
index.html
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Подключите кнопки корзины</title>
</head>
<body>
<p role="status">Корзина · <span id="cart-count">0</span></p>
<button id="add" type="button">В корзину</button>
<button id="clear" type="button">Очистить корзину</button>
<script src="script.js"></script>
</body>
</html>
script.js
const count = document.querySelector("#cart-count");
const add = document.querySelector("#add");
const clear = document.querySelector("#clear");
let quantity = 0;
function renderCart() {
count.textContent = quantity;
console.log("Количество в корзине:", quantity);
}
function addProduct() {
quantity++;
renderCart();
}
function clearCart() {
quantity = 0;
renderCart();
}
// Подключите оба обработчика и покажите начальное количество.
Нажмите «Запустить», чтобы увидеть результат.
Задание. Добавьте или уберите мяч
Дополните корзину мяча двумя действиями.
-
В
addProduct()увеличивайтеquantityна единицу и вызывайте готовуюrenderCart(). -
В
removeProduct()уменьшайте количество только приquantity > 0, затем обновляйте корзину. -
В готовом блоке проверки кнопок подключите эти функции через
addEventListener("click", ...)кaddButtonиremoveButtonсоответственно. Передавайте сами функции, не результаты их вызовов.
Сохраните внешнюю переменную количества и начальный вызов renderCart().
Ожидаемый результат
- При запуске —
Товаров: 0, сумма: 0 ₽. - Два добавления дают
Товаров: 2, сумма: 900 ₽и классis-readyу корзины. - Одно удаление оставляет
Товаров: 1, сумма: 450 ₽. -
После удаления последнего мяча количество и сумма равны нулю, класс
is-readyубран. Дополнительные удаления оставляют ноль.
Проверьте также кнопки клавиатурой и повторный запуск примера.
Выполните задание
Условие задания
index.html
<main>
<h1>Лавка Тони</h1>
<article class="product">
<h2>Мяч для прогулок</h2>
<p>450 ₽ за штуку</p>
<button id="add" type="button">В корзину</button>
</article>
<section class="cart" id="cart" aria-labelledby="cart-title">
<h2 id="cart-title">Корзина</h2>
<p id="summary" role="status">Товаров: 0, сумма: 0 ₽</p>
<button id="remove" type="button" aria-label="Уменьшить количество: Мяч для прогулок">−</button>
</section>
</main>
main.js
const price = 450;
let quantity = 0;
const addButton = document.querySelector("#add");
const removeButton = document.querySelector("#remove");
const summary = document.querySelector("#summary");
const cart = document.querySelector("#cart");
function renderCart() {
if (summary !== null && cart !== null) {
summary.textContent = "Товаров: " + quantity + ", сумма: " + price * quantity + " ₽";
console.log(summary.textContent);
cart.classList.toggle("is-ready", quantity > 0);
}
}
function addProduct() {
// Увеличьте quantity и обновите корзину.
}
function removeProduct() {
// Уменьшите quantity, если есть товар, и обновите корзину.
}
if (addButton !== null && removeButton !== null) {
// Подключите функции к click соответствующих кнопок.
}
renderCart();
style.css
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 16px;
background: #faf7f0;
color: #29251f;
font-family: system-ui, sans-serif;
line-height: 1.5;
overflow-wrap: anywhere;
}
main {
max-width: 640px;
margin: auto;
}
h1, h2, h3 {
line-height: 1.2;
}
.product, .cart {
margin-block: 12px;
padding: 16px;
border: 2px solid #b3a58c;
border-radius: 8px;
background: #fff;
}
.product h3 {
margin-top: 0;
}
.is-muted {
color: #665c4c;
border-style: dashed;
}
.is-selected, .is-ready {
border-color: #246341;
background: #edf7ef;
}
.is-unavailable .availability {
color: #9c2828;
font-weight: 700;
}
button {
max-width: 100%;
padding: .7rem 1.4rem;
border: 2px solid saddlebrown;
border-radius: 999px;
background: saddlebrown;
color: white;
font: inherit;
font-weight: 650;
cursor: pointer;
}
button:focus-visible {
outline: 3px solid #287a86;
outline-offset: 4px;
}
button + button {
margin-top: 8px;
}
Нажмите «Запустить», чтобы увидеть результат.
Подсказка
Регистрация добавления: addButton.addEventListener("click", addProduct). Удаление подключается так
же, но с другой функцией. Проверка перед уменьшением не даёт получить отрицательное количество. Вызов
renderCart() нужен после изменения данных, чтобы страница показала новое состояние.
Что уже умеет наша программа
Кнопки добавляют и убирают мячи. Количество хранится между нажатиями, а после каждого изменения на странице видна новая сумма. На этом базовая часть учебника завершена. Дальше вас ждёт урок «Дерево DOM». А пока можно попробовать собрать корзину самостоятельно.
Проект по желанию Корзина с доставкой
Покупатель хочет видеть, сколько он заплатит за мячи с учётом доставки. HTML и CSS уже готовы. В JavaScript есть объект товара с ценой 450 рублей и запасом 3 мяча. Напишите обработчики кнопок и рассчитайте итог заказа.
- Кнопки добавляют один мяч, убирают один и очищают корзину. Количество не должно становиться отрицательным или превышать запас. Добавление сверх запаса и удаление из пустой корзины оставляют количество прежним.
- Курьерская доставка стоит 150 рублей, а при сумме товаров от 1000 рублей включительно бесплатна. У пустой корзины стоимость товаров, доставка и итог равны нулю.
-
Покажите название, количество, стоимость товаров, доставку и итог в сводке. Класс
is-readyдолжен присутствовать у корзины только при положительном количестве.
- При запуске сразу покажите пустую корзину. После каждого действия обновляйте сводку.
- Используйте цену и запас из объекта: при изменении этих данных программа должна продолжать считать правильно. Формат текста можно выбрать свой, если все значения подписаны.
- Проверьте кнопки мышью и клавиатурой, а затем скачайте HTML и повторите действия в отдельной вкладке. Перезагрузка начинает корзину с нуля.
| Действие | Количество | Товары | Доставка | Итог |
|---|---|---|---|---|
| Начало | 0 | 0 | 0 | 0 |
| Добавить один мяч | 1 | 450 | 150 | 600 |
| Добавить второй | 2 | 900 | 150 | 1050 |
| Добавить третий | 3 | 1350 | 0 | 1350 |
| Попытаться добавить четвёртый | 3 | 1350 | 0 | 1350 |
| Убрать один мяч | 2 | 900 | 150 | 1050 |
| Очистить, затем убрать ещё одну | 0 | 0 | 0 | 0 |
- Для проверки границы временно задайте цену 500 рублей: два мяча дают ровно 1000 рублей и бесплатную доставку.
- При запасе 0 добавление оставляет пустую корзину.
В этой работе цена — положительное целое число рублей, запас — целое неотрицательное число. Не меняйте эти правила ради неизвестных входных данных.
Соберите корзину с доставкой
Условие задания
index.html
<main>
<h1>Лавка Тони</h1>
<p>Добавляйте и убирайте мяч. Условия доставки указаны в задании.</p>
<section id="cart" class="cart" aria-labelledby="cart-title">
<h2 id="cart-title">Корзина</h2>
<p id="summary" role="status">Здесь появится расчёт вашей программы.</p>
<div class="actions">
<button id="add" type="button" aria-label="Увеличить количество: Мяч для прогулок">+</button>
<button id="remove" type="button" aria-label="Уменьшить количество: Мяч для прогулок">−</button>
<button id="reset" type="button">Очистить корзину</button>
</div>
</section>
</main>
main.js
const product = { name: "Мяч для прогулок", price: 450, stock: 3 };
// Напишите программу по условию. HTML и CSS уже подготовлены.
// Сами выберите переменные, функции и последовательность действий.
style.css
body {
margin: 0;
padding: 16px;
font-family: system-ui, sans-serif;
line-height: 1.5;
background: #fff;
color: #222;
}
/* Рамка помогает проверить состояние, текст сводки передаёт тот же смысл. */
.cart {
padding: 16px;
border: 2px solid #777;
}
.cart.is-ready {
border-color: #246341;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
button {
padding: 8px 12px;
font: inherit;
}
button:focus-visible {
outline: 3px solid #246341;
outline-offset: 3px;
}
Нажмите «Запустить», чтобы увидеть результат.
Подсказка: с чего начать
Сначала запишите шаги словами: какие данные сохраняются, что меняет каждая кнопка, что нужно пересчитать. Добейтесь правильного начального вывода, затем добавляйте действия по одному.
Подсказка: как разделить программу
Храните количество между вызовами. Расчёт доставки можно вынести в отдельную функцию с результатом, а обновление текста и класса — в другую. Обработчик меняет данные и просит обновить страницу.
Перед просмотром решения сверьте корзину с таблицей. Объясните, почему после удаления третьего мяча доставка снова становится платной и в какой момент обработчик обновляет итог на странице.