Автоматическая перестановка карточек .show (в портфолио) jQuery CSS html

Я хотел создать портфолио с эффектом фильтра карточек (чтобы при нажатии кнопки отображались только соответствующие карточки для выбранной категории и чтобы скрыть другие нерелевантные карточки). Для этого я разделил карточки на 2 категории (классы) как книги и статьи.

когда я нажимаю кнопку «статьи», карточки .show остаются на своем исходном месте в сетке (UI), а места для карточек .hide в пользовательском интерфейсе выглядят пустыми, а не перестраиваются карточки .show для заполнения пробелов.

Поэтому нужно сделать так, чтобы карты отображались автоматически, не показывая пустых мест в (UI).

при нажатии кнопки "все"

при нажатии на кнопку "статьи"

<script>
    $(document).ready(function(){
        $(".all").click(function(){
        $(".all").show();
    });

    $(".booksB").click(function(){
        $(".books").show();$(".articles").hide()
        });

        $(".articlesB").click(function(){
        $(".books").hide();$(".articles").show()
    });
    });

HTML-коды

<section class = "banner" style = "background: linear-gradient(to bottom right,hsl(0, 100%, 2%),white); width: auto; padding: 100px 0 200px;"> 
    <section id = "portfolio" class = "portfolio">
      <div class = "row aos-int aos-animate" data-aos = "fade-up" data-aos-delay = "100">
        <div class = "col-lg-12 d-flex justify content-center">
          <div class = "empty " style = "width: auto; margin-top: 80px;">

          </div>
          <div id = "myBtnContainer" style= " margin-top:-200px ;margin: auto ; align-items: center;">
            <button class = "all button-33 active" role = "button" ; onclick = "fb1">All</button>
            <button class = "booksB button-33" role = "button" onclick = "fb2">Books</button>
            <button class = "articlesB button-33" role = "button"  ; onclick = "fb3">Articles</button>
           
          </div>
        </div>
      </div>
    </section>
    <div class = "container" >
      <div class = "row "style = "margin: auto;  align-items: center;">
        <div class = "col-lg-3 col-md-6 portfolio-item " style = "justify-content: center;" >
          <div class = "all books"> 
            <div class = "card shadow bg-light mb-3 filterDiv book" style = "max-width: 18rem;">
              <img src = "img/bookRZ.jpg" class = "card-img-top embed-responsive embed-responsive-4by3"  alt = "Drops of Ocean">
              <div class = "card-body">
                <h5 class = "card-title">Albert Einstein - Drops on the Ocean</h5>
                <p class = "card-text">Biography <br> <br>
                  Publisher: Sanhinda Publishers
                </p>
                <a href = "https://www.daraz.lk/products/albert-einstein-sindu-matha-bindu-i122874161.html" class = "btn btn-primary">Buy Online</a>
              </div>
            </div>
          </div>  
        </div>
        <div class = "col-lg-3 col-md-6 portfolio-item " style = "justify-content: center;" >
          <div class = "all books"> 
            <div class = "card shadow bg-light mb-3 filterDiv book" style = "max-width: 18rem;">
              <img src = "img/book05268.jpg" class = "card-img-top embed-responsive embed-responsive-4by3"  alt = "Drops of Ocean">
              <div class = "card-body">
                <h5 class = "card-title">Asandimiththa -translation</h5>
                <p class = "card-text">Biography <br> <br>
                  Publisher: Sarasavi Publishers
                </p>
                <a href = "https://www.daraz.lk/products/albert-einstein-sindu-matha-bindu-i122874161.html" class = "btn btn-primary">Buy Online</a>
              </div>
            </div>
          </div>  
        </div>
        <div class = "col-lg-3 col-md-6 portfolio-item " style = "justify-content: center;" >
          <div class = "all articles"> 
            <div class = "card shadow bg-light mb-3 filterDiv " style = "max-width: 18rem;">
              <img src = "img/bookRZ.jpg" class = "card-img-top embed-responsive embed-responsive-4by3"  alt = "Drops of Ocean">
              <div class = "card-body">
                <h5 class = "card-title">Article 01</h5>
                <p class = "card-text">Biography <br> <br>
                  Mora Spirit 
                </p>
                <a href = "https://www.daraz.lk/products/albert-einstein-sindu-matha-bindu-i122874161.html" class = "btn btn-primary">Buy Online</a>
              </div>
            </div>
          </div>  
        </div>
        <div class = "col-lg-3 col-md-6 portfolio-item " style = "justify-content: center;" >
          <div class = "all articles"> 
            <div class = "card shadow bg-light mb-3 filterDiv " style = "max-width: 18rem;">
              <img src = "img/bookRZ.jpg" class = "card-img-top embed-responsive embed-responsive-4by3"  alt = "Drops of Ocean">
              <div class = "card-body">
                <h5 class = "card-title">Article 02</h5>
                <p class = "card-text">Biography <br> <br>
                  Mora Spirit
                </p>
                <a href = "https://www.daraz.lk/products/albert-einstein-sindu-matha-bindu-i122874161.html" class = "btn btn-primary">Buy Online</a>
              </div>
            </div>
          </div>  
        </div>
        <div class = "col-lg-3 col-md-6 portfolio-item " style = "justify-content: center;" >
          <div class = "all articles"> 
            <div class = "card shadow bg-light mb-3 filterDiv " style = "max-width: 18rem;">
              <img src = "img/bookRZ.jpg" class = "card-img-top embed-responsive embed-responsive-4by3"  alt = "Drops of Ocean">
              <div class = "card-body">
                <h5 class = "card-title">Article 04</h5>
                <p class = "card-text">Biography <br> <br>
                  Mora spirit
                </p>
                <a href = "https://www.daraz.lk/products/albert-einstein-sindu-matha-bindu-i122874161.html" class = "btn btn-primary">Buy Online</a>
              </div>
            </div>
          </div>  
        </div>
        <div class = "col-lg-3 col-md-6 portfolio-item " style = "justify-content: center;" >
          <div class = "all books"> 
            <div class = "card shadow bg-light mb-3 filterDiv book" style = "max-width: 18rem;">
              <img src = "img/bookRZ.jpg" class = "card-img-top embed-responsive embed-responsive-4by3"  alt = "Drops of Ocean">
              <div class = "card-body">
                <h5 class = "card-title">Book 03</h5>
                <p class = "card-text">Biography <br> <br>
                  Publisher: Sarasavi
                </p>
                <a href = "https://www.daraz.lk/products/albert-einstein-sindu-matha-bindu-i122874161.html" class = "btn btn-primary">Buy Online</a>
              </div>
            </div>
          </div>  
        </div>
        <div class = "col-lg-3 col-md-6 portfolio-item " style = "justify-content: center;" >
          <div class = "all articles"> 
            <div class = "card shadow bg-light mb-3 filterDiv book" style = "max-width: 18rem;">
              <img src = "img/bookRZ.jpg" class = "card-img-top embed-responsive embed-responsive-4by3"  alt = "Drops of Ocean">
              <div class = "card-body">
                <h5 class = "card-title">Article 06</h5>
                <p class = "card-text">Biography <br> <br>
                  Sunday Observer
                </p>
                <a href = "https://www.daraz.lk/products/albert-einstein-sindu-matha-bindu-i122874161.html" class = "btn btn-primary">Buy Online</a>
              </div>
            </div>
          </div>  
        </div>
    </div>  
  </section> 

пожалуйста, помогите мне, ребята

Пожалуйста, добавьте также необходимый HTML

ruleboy21 16.03.2022 19:54

@ruleboy21 Я добавил их..

Hesin Alwis 16.03.2022 20:12
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
2
28
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

С частью JavaScript все в порядке, но вы добавили целевые классы не к тем элементам. Вместо этого вы должны добавить целевые классы (.all, .books, .articles) в элемент .portfolio-item.

Пример: изменить

<div class = "col-lg-3 col-md-6 portfolio-item " style = "justify-content: center;" >
    <div class = "all books"> 
        <div class = "card shadow bg-light mb-3 filterDiv book" style = "max-width: 18rem;">
            <img src = "img/bookRZ.jpg" class = "card-img-top embed-responsive embed-responsive-4by3"  alt = "Drops of Ocean">
            <div class = "card-body">
                <h5 class = "card-title">Albert Einstein - Drops on the Ocean</h5>
                <p class = "card-text">Biography <br> <br>
                    Publisher: Sanhinda Publishers
                </p>
                <a href = "https://www.daraz.lk/products/albert-einstein-sindu-matha-bindu-i122874161.html" class = "btn btn-primary">Buy Online</a>
            </div>
        </div>
    </div>  
</div>

К этому

<div class = "col-lg-3 col-md-6 portfolio-item all books" style = "justify-content: center;" >
    <div> 
        <div class = "card shadow bg-light mb-3 filterDiv book" style = "max-width: 18rem;">
            <img src = "img/bookRZ.jpg" class = "card-img-top embed-responsive embed-responsive-4by3"  alt = "Drops of Ocean">
            <div class = "card-body">
                <h5 class = "card-title">Albert Einstein - Drops on the Ocean</h5>
                <p class = "card-text">Biography <br> <br>
                    Publisher: Sanhinda Publishers
                </p>
                <a href = "https://www.daraz.lk/products/albert-einstein-sindu-matha-bindu-i122874161.html" class = "btn btn-primary">Buy Online</a>
            </div>
        </div>
    </div>  
</div>

Большое спасибо .. Это работает .. Большое спасибо

Hesin Alwis 16.03.2022 21:03

Другие вопросы по теме