Poprzednie zadanie
Znajdowanie i modyfikowanie elementów DOM4/7
Wróć do listy zadań
  1. 1. Подключение нескольких скриптов
  2. 2. Переменная-счётчик
  3. 3. Инкремент и декремент
  4. 4. Метод classList.contains, проверка наличия класса
  5. 5. Условная конструкция if
  6. 6. Конструкция else, альтернативная ветка
  7. 7. Изменяем значение из разметки
Następne zadanie
  • Kursy
  • Rejestracja
  • Zaloguj się

Caricamento...
In pochi secondi sarà pronto.

  • Teoria
  • Teoria

Метод classList.contains, проверка наличия класса

Отлично! Мы создали счётчик лайков, значение которого увеличивается при каждом клике. Но ведь число лайков не должно только расти.

Если пользователь ещё не ставил лайк, то клик на «сердечко» должен увеличивать счётчик. А если лайк уже есть, то клик должен уменьшать счётчик. Как нам различать эти клики?

Мы можем проверить, есть ли у элемента heart класс added. Если класса у элемента ещё нет, то лайк добавляется, а если класс уже есть, то лайк снимается.

Чтобы проверить, есть ли у элемента класс, используем метод classList.contains:

элемент.classList.contains('класс');

В скобках указывается класс, наличие которого нужно проверить. Метод classList.contains вернёт true, если класс у элемента есть, и false, если класса нет.

Значения true и false называют булевыми.

Посмотрим, как работает метод classList.contains: скажем JavaScript выводить в консоль значения, которые этот метод возвращает, и кликнем несколько раз на «сердечко», чтобы переключить класс.

Todos los archivos
    <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="setting.css"> <link rel="stylesheet" href="style.css"> <title>FlashNews!</title> </head> <body class="page light-theme"> <header class="page-header"> <div class="container"> <span class="header-logo"> <img src="img/main-logo.svg" width="67" height="29" alt="Логотип портала FlashNews!"> </span> <button class="theme-button" type="button">Изменить тему</button> </div> </header> <main class="inner-news"> <article class="container"> <h1 class="inner-heading">🔥 Шок! Скандал! Сенсация!</h1> <div class="news-full"> <img src="img/news-robot2.jpg" alt="Робот на курорте"> <div class="news-stats"> <button class="heart" type="button"><span class="likes-number"></span></button> <time datetime="2019-12-22">22 декабря 2019</time> </div> <p>Оказывается, для того, чтобы начать программировать на JavaScript, необязательно быть котом! Учёные создали первого робота, который может развиваться и изменять свой код. Он сразу же научился верстать сайты и уехал фрилансить на Бали.</p> </div> </article> </main> <footer class="page-footer"> <div class="container"> <p>© FlashNews!</p> <span class="footer-logo"> <img src="img/white-logo.svg" alt="Логотип портала FlashNews!"> </span> </div> </footer> <script src="themes.js"></script> <script src="likes.js"></script> </body> </html>
    /* стили страницы новости */ .comment-form { display: flex; margin-bottom: 30px; padding: 20px 12px; } .comment-inner { position: relative; flex-grow: 1; margin-right: 10px; } .comment-label { position: absolute; top: -16px; left: -9px; padding: 4px 8px; font-size: 10px; line-height: 14px; } .comment-field { width: 100%; height: 30px; padding: 0 10px; border: none; background-color: transparent; font: inherit; font-size: 14px; line-height: 30px; } .comment-field::placeholder { color: #aaaaaa; font: inherit; font-size: 14px; font-style: italic; } .comment-field:focus::placeholder { font-size: 0; } .comment-field:hover::placeholder, .comment-field:active::placeholder { opacity: 0.5; } .inner-news .inner-heading { margin-bottom: 20px; font-size: 24px; } .news-full { display: flex; flex-direction: column; margin-bottom: 24px; } .news-full img { margin-bottom: 4px; width: 100%; height: 220px; object-fit: cover; } .news-full .news-stats { display: flex; justify-content: space-between; } .news-full .heart { padding: 12px 10px; min-width: 40px; min-height: 34px; font-family: inherit; font-weight: bold; font-size: 16px; border: none; background-color: transparent; background-repeat: no-repeat; background-position: 12px; cursor: pointer; } .heart .likes-number { margin-left: 24px; line-height: 14px; } .news-full time { margin-top: 14px; margin-right: 12px; margin-bottom: 8px; margin-left: 0; } .news-full p { margin-top: 0; margin-right: 12px; margin-bottom: 16px; margin-left: 12px; font-size: 14px; line-height: 24px; } .comment-feed h2 { margin-top: 0; margin-bottom: 12px; } .comment-list { margin-top: 0; margin-right: 0; margin-bottom: 12px; margin-left: 0; padding: 0; list-style: none; counter-reset: comments; } .comment-list li { margin-bottom: 6px; padding: 10px 12px; min-height: 36px; font-size: 14px; line-height: 24px; } .comment-list .user-comment { position: relative; display: flex; } .comment-list .user-comment::before { counter-increment: comments; content: "#" counter(comments); padding-right: 12px; margin-right: 12px; border-right: 1px solid; font-weight: bold; } .comment-list .user-comment::after { position: absolute; content: ""; width: 0; height: 0; bottom: 0; left: -8px; border: 4px solid; border-left-color: transparent; border-top-color: transparent; } @keyframes comment-blink-light { 0% { background-color: #b6aaff; opacity: 0; } 20% { opacity: 0.8; } } @keyframes comment-blink-light-after { 0% { border-right-color: #b6aaff; border-bottom-color: #b6aaff; opacity: 0; } 20% { opacity: 0.8; } } @keyframes comment-blink-dark { 0% { background-color: #473c8d; opacity: 0; } 20% { opacity: 1; } } @keyframes comment-blink-dark-after { 0% { border-right-color: #473c8d; border-bottom-color: #473c8d; opacity: 0; } 20% { opacity: 1; } } /* темы */ .dark-theme .header-logo { filter: invert(1) hue-rotate(180deg) brightness(2); } /* Светлая тема */ .light-theme { color: #333333; background-color: #eae9f2; } .light-theme .page-header { background-color: #ffffff; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2); } .light-theme .header-link { color: #6653d9; } .light-theme .header-link::before { background-image: url("img/arrow-back-light.svg"); background-repeat: no-repeat; background-position: 0 0; } .light-theme .theme-button { color: #6653d9; border: 1px solid #6653d9; } .light-theme .theme-button::before { background-image: url("img/moon-normal.svg"); } .light-theme .theme-button:focus, .light-theme .theme-button:hover { color: #ffffff; background-color: #6653d9; } .light-theme .theme-button:focus { outline-color: #b6aaff; } .light-theme .theme-button:focus::before, .light-theme .theme-button:hover::before { background-image: url("img/moon-hover.svg"); } .light-theme .menu-open { background-color: #ffffff; background-image: url("img/menu-open-light.svg"); } .light-theme .menu:focus { outline-color: #b6aaff; } .light-theme .menu-open:focus, .light-theme .menu-open:hover { background-color: #6653d9; background-image: url("img/menu-open-dark.svg"); } .light-theme .menu-close { background-color: #6653d9; } .light-theme .menu-close:focus, .light-theme .menu-close:hover { background-color: #473c8d; } .light-theme .main-menu { background-color: #6653d9; color: #ffffff; } .light-theme .main-menu a:focus, .light-theme .main-menu a:hover { background-color: #473c8d; } .light-theme .main-menu a:focus { outline-color: #b6aaff; } .light-theme .news-view button { border: 1px solid #6653d9; color: #6653d9; } .light-theme .news-view button:focus, .light-theme .news-view button:hover, .light-theme .news-view button:active, .light-theme .news-view .view-checked { background-color: #6653d9; color: #ffffff; } .light-theme .news-view button:focus { outline-color: #b6aaff; } .light-theme .news-view .row-view:focus::before, .light-theme .news-view .row-view:hover::before, .light-theme .news-view .row-view:active::before { background-image: url("img/rows-light-checked.svg"); } .light-theme .news-view .tile-view:focus::before, .light-theme .news-view .tile-view:hover::before, .light-theme .news-view .tile-view:active::before { background-image: url("img/tiles-light-checked.svg"); } .light-theme .row-view::before { background-image: url("img/rows-light.svg"); } .light-theme .tile-view::before { background-image: url("img/tiles-light.svg"); } .light-theme .row-view.view-checked::before { background-image: url("img/rows-light-checked.svg"); } .light-theme .tile-view.view-checked::before { background-image: url("img/tiles-light-checked.svg"); } .light-theme .new-block { background-color: #ffffff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2); } .light-theme .news-full { background-color: #ffffff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2); } .light-theme .new-block time { color: #aaaaaa; } .light-theme .news-full time { color: #aaaaaa; } .light-theme .cookies-agreement { background-color: #fdeacd; box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.2); } .light-theme .button { background-color: #6653d9; color: #ffffff; } .light-theme .button:focus, .light-theme .button:hover { background-color: #473c8d; } .light-theme .button:focus { outline-color: #b6aaff; } .light-theme .page-footer { background-color: #6653d9; color: #ffffff; } .light-theme .subscription, .light-theme .comment-form { background-color: #ffffff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2); } .light-theme .subscription-message { background-color: #6653d9; color: #eae9f2; } .light-theme .subscription-message::before { background-image: url("img/icon-ok-light.svg"); } .light-theme .subscription-label, .light-theme .comment-label { color: #6653d9; } .light-theme .subscription-email, .light-theme .comment-field { border: 1px solid #eae9f2; color: #333333; } .light-theme .heart { color: #6653d9; background-image: url("img/icon-heart-light.svg"); opacity: 0.7; } .light-theme .heart.added { background-image: url("img/icon-heart-light-added.svg"); } .page .heart:focus, .page .heart:hover { opacity: 1; } .light-theme .heart:focus { outline-color: #b6aaff; } .light-theme .heart:active { opacity: 1; background-image: url("img/icon-heart-light-active.svg"); } .light-theme .comment-list li { background-color: #ffffff; } .light-theme .user-comment:not(:first-child) { animation: comment-blink-light 600ms ease-in; } .light-theme .user-comment::before { border-right-color: #eae9f2; color: #cdcdcd; } .light-theme .user-comment::after { border-right-color: #ffffff; border-bottom-color: #ffffff; } .light-theme .user-comment:not(:first-child)::after { animation: comment-blink-light-after 600ms ease-in; } .light-theme .comment-label { background-color: #ffffff; } .light-theme .comment-field:focus { outline-color: #b6aaff; } /* Тёмная тема */ .dark-theme { color: #f2f2f2; background-color: #17161a; } .dark-theme .page-header { background-color: #373540; box-shadow: 0 2px 2px rgba(0, 0, 0, 0.6); } .dark-theme .header-link { color: #9484f2; } .dark-theme .header-link::before { background-image: url("img/arrow-back-dark.svg"); background-repeat: no-repeat; background-position: 0 0; } .dark-theme .theme-button { color: #9484f2; border: 1px solid #9484f2; } .dark-theme .theme-button::before { background-image: url("img/sun-normal.svg"); } .dark-theme .theme-button:focus, .dark-theme .theme-button:hover { color: #17161a; background-color: #9484f2; } .dark-theme .theme-button:focus { outline-color: #6653d9; } .dark-theme .theme-button:focus::before, .dark-theme .theme-button:hover::before { background-image: url("img/sun-hover.svg"); } .dark-theme .menu:focus { outline-color: #6653d9; } .dark-theme .menu-open { background-color: #373540; background-image: url("img/menu-open-dark.svg"); } .dark-theme .menu-open:focus, .dark-theme .menu-open:hover { background-color: #473c8d; background-image: url("img/menu-open-dark.svg"); } .dark-theme .menu-close { background-color: #473c8d; } .dark-theme .menu-close:focus, .dark-theme .menu-close:hover { background-color: #6653d9; } .dark-theme .main-menu { background-color: #473c8d; color: #f2f2f2; } .dark-theme .main-menu a:focus { outline-color: #6653d9; } .dark-theme .main-menu a:focus, .dark-theme .main-menu a:hover { background-color: #6653d9; } .dark-theme .news-view button { border: 1px solid #9484f2; color: #9484f2; } .dark-theme .news-view button:focus { outline-color: #6653d9; } .dark-theme .news-view button:focus, .dark-theme .news-view button:hover, .dark-theme .news-view button:active, .dark-theme .news-view .view-checked { background-color: #9484f2; color: #17161a; } .dark-theme .news-view .row-view:focus::before, .dark-theme .news-view .row-view:hover::before, .dark-theme .news-view .row-view:active::before { background-image: url("img/rows-dark-checked.svg"); } .dark-theme .news-view .tile-view:focus::before, .dark-theme .news-view .tile-view:hover::before, .dark-theme .news-view .tile-view:active::before { background-image: url("img/tiles-dark-checked.svg"); } .dark-theme .row-view::before { background-image: url("img/rows-dark.svg"); } .dark-theme .tile-view::before { background-image: url("img/tiles-dark.svg"); } .dark-theme .row-view.view-checked::before { background-image: url("img/rows-dark-checked.svg"); } .dark-theme .tile-view.view-checked::before { background-image: url("img/tiles-dark-checked.svg"); } .dark-theme .new-block { background-color: #2a2930; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6); } .dark-theme .news-full { background-color: #2a2930; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6); } .dark-theme .new-block time { color: #888888; } .dark-theme .news-full time { color: #888888; } .dark-theme .cookies-agreement { background-color: #473c8d; box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.6); } .dark-theme .button { background-color: #9484f2; color: #17161a; } .dark-theme .button:focus { outline-color: #6653d9; } .dark-theme .button:focus, .dark-theme .button:hover { background-color: #b6aaff; } .dark-theme .page-footer { background-color: #0a0910; color: #f2f2f2; } .dark-theme .subscription, .dark-theme .comment-form { background-color: #2a2930; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.6); } .dark-theme .subscription-message { background-color: #9484f2; color: #17161a; } .dark-theme .subscription-message::before { background-image: url("img/icon-ok-dark.svg"); } .dark-theme .subscription-label, .dark-theme .comment-label { color: #9484f2; } .dark-theme .comment-label { background-color: #2a2930; } .dark-theme .subscription-email, .dark-theme .comment-field { border: 1px solid #473c8d; color: #f2f2f2; } .dark-theme .heart { color: #9484f2; background-image: url("img/icon-heart-dark.svg"); opacity: 0.7; } .dark-theme .heart:focus { outline-color: #6653d9; } .dark-theme .heart.added { background-image: url("img/icon-heart-dark-added.svg"); } .dark-theme .heart:active { opacity: 1; background-image: url("img/icon-heart-dark-active.svg"); } .dark-theme .comment-list li { background-color: #2a2930; } .dark-theme .user-comment:not(:first-child) { animation: comment-blink-dark 600ms ease-in; } .dark-theme .user-comment::before { border-right-color: #17161a; color: rgba(255, 255, 255, 0.3); } .dark-theme .user-comment::after { border-right-color: #2a2930; border-bottom-color: #2a2930; } .dark-theme .user-comment:not(:first-child)::after { animation: comment-blink-dark-after 600ms ease-in; } .dark-theme .comment-field:focus { outline-color: #6653d9; }
    let heart = document.querySelector('.heart'); let likesNumber = document.querySelector('.likes-number'); let counter = 0; heart.onclick = function () { // Добавьте код сюда counter++; likesNumber.textContent = counter; heart.classList.toggle('added'); };
    let page = document.querySelector('.page'); let themeButton = document.querySelector('.theme-button'); themeButton.onclick = function () { page.classList.toggle('light-theme'); page.classList.toggle('dark-theme'); };

    Il codice è cambiato, fai clic su "Aggiorna" o attiva l'esecuzione automatica.

    Sei passato a un'altra pagina

    Fare clic all'interno del mini-browser per evidenziare questa finestra.

    100%
    Consola
    ObiettiviFatto
    0
      1. На 6 строке напишите инструкцию console.log(heart.classList.contains('added'));.
      2. Нажмите на «сердечко».
      3. Откройте консоль. В момент клика класса added у элемента ещё не было, поэтому вывелось false.
      4. Ещё раз нажмите на «сердечко».
      5. Откройте консоль. В момент клика класс added у элемента был, поэтому вывелось true.

      © 2023-2024, bobrkode.com