javascript - ¿Cómo puedo crear una galería de portafolio con filtrado en mi sitio web sin romper el resto de mi código? / ¿Por q

CorePress2024-01-25  488

He estado intentando codificar una galería de portafolios con filtrado en mi sitio web usando HTML, CSS y Javascript. Miré varios tutoriales (w3Schools, Geeks for Geeks) y los seguí exactamente, pero ninguno funcionó. Con w3Schools, me quedé con un área de contenido del cuerpo completamente vacía, y con Geeks for Geeks, tenía imágenes en el área de contenido del cuerpo, pero mi barra lateral y la barra de navegación estaban totalmente destrozadas a pesar de que los cambios en el código no estaban relacionados. a ellos.

Entonces, esto es lo que intento hacer: tengo una página web que se ve así y quiero filtrar los bloques por su color cuando hago clic en los botones de la barra de navegación. Entonces, si hiciera clic en amarillo, el resultado se vería así. (La cuadrícula real de imágenes es de 3x3 y hay dos amarillas.bloques bajos en él.) Quiero que se ordenen correctamente en tres columnas tanto como sea posible.

EDITAR: Aquí está mi código original con errores, las soluciones están en los comentarios:

<!DOCTYPE html>
   <head>
      <meta charset="UTF-8">
      <title>Mozart Armstrong Portfolio Graphic Design</title>
         <style>

            @font-face {
              font-family: Klik;
              src: url(klik-light-webfont.woff);
            }

            @font-face {
              font-family: theBoldFont;
              src: url(theboldfont.ttf);
            }

            .main {
              margin-left: 200px;
              padding: 105px 10px;
              font-size: 16px;
              font-family: CaviarDreams;
              color: #000000;
              display: block;
              column-count: 3;
              column-width: 32%
              column-gap: 1%;
            }

            .main p {
              font-size: 24px;
              font-family: CaviarDreams;
              color: #000000;
            }
            
            .sidebar {
              height: 100%;
              width: 200px;
              position: fixed;
              z-index: 3;
              top: 0;
              left: 0;
              background-color: #000000;
              overflow-x: hidden;
              padding-top: 20px;
            }

            .sidebar a {
              padding: 6px 8px 6px 16px;
              text-decoration: none;
              font-size: 16px;
              font-family: CaviarDreams;
              color: #ffffff;
              display: block;
            }

            .sidebar a:hover {
              color: #808080;
            }

            .sidebar b {
              padding: 6px 8px 6px 16px;
              text-decoration: none;
              font-family: theBoldFont;
              font-size: 28px;
              color: #ffffff;
              display: block;
            }

            .sidebar c {
              padding: 6px 8px 6px 16px;
              text-decoration: none;
              font-size: 13px;
              font-family: Klik;
              color: #ffffff;
              display: block;
            }

            .navbar {
              position: absolute;
              padding: 10px 0px 10px 10px;
              height: 100px;
              width: 100%;
              right: 0;
              top: 0;
              z-index: 2;
              overflow-x: hidden;
              background-color: #808080;
            }

            .navbar a {
              padding: 20px 8px 16px 16px;
              text-decoration: none;
              font-size: 16px;
              font-family: Klik;
              color: #ffffff;
            }

            .navbar b {
              padding: 0px 0px 0px 0px;
              width: 225px;
              text-decoration: none;
              font-size: 16px;
              font-family: Klik;
              color: #ffffff;
              display: inline-block;
            }

            .navbar c {
              padding: 25px 225px 0px 245px;
              width: 100%;
              height: 30px;
              text-decoration: none;
              font-size: 26px;
              font-family: theBoldFont;
              color: #000000;
              display: inline-block;
            }

            .navbar button {
              background-color: #000000;
              border: none;
              color: #ffffff;
              padding: 10px 32px;
              text-align: center;
              text-decoration: none;
              display: inline-block;
              font-size: 16px;
              font-family: Klik;
            }

            .navbar button:hover {
              background-color: #ffffff;
              border: none;
              color: #000000;
              padding: 10px 32px;
              text-align: center;
              text-decoration: none;
              display: inline-block;
              font-size: 16px;
              font-family: Klik;
            }

            
         </style>
   </head>
   <body>
      <div class="sidebar">
         <b>Mozart</b>
         <b>Armstrong</b>
         <c>design • marketing • branding</c>
         <b></b>
         <b></b>
         <b></b>
         <a href="">Graphic Design</a>
         <a href="">Illustration</a>
         <a href="">Animations</a>
         <a href="">Photography</a>
         <a href="">Writing</a>
         <a href="">Fashion Design</a>
         <b></b>
         <b></b>
         <a href="">About</a>
      </div>
       <div class="navbar">
         <c>Graphic Design</c>
         <b></b>
         <button onclick="">All</button>
         <button onclick="">Red</button>
         <button onclick="">Yellow</button>
         <button onclick="">Green</button>
         <button onclick="">Blue</button>
         <button onclick="">Pink</button>
       </div>
      <div class="main">
        <p></p><img src="https://stackoverflow.com/questions/66843501/Block2.png" width=100%></img><p></p><img src="https://stackoverflow.com/questions/66843501/Block.png" width=100%></img><p></p><img src="https://stackoverflow.com/questions/66843501/Block3.png" width=100%></img><nextcol>
        <p></p><img src="https://stackoverflow.com/questions/66843501/Block4.png" width=100%></img><p></p><img src="https://stackoverflow.com/questions/66843501/Block.png" width=100%></img><p></p><img src="https://stackoverflow.com/questions/66843501/Block2.png" width=100%></img><nextcol>
        <p></p><img src="https://stackoverflow.com/questions/66843501/Block5.png" width=100%><p></p><img src="https://stackoverflow.com/questions/66843501/Block3.png" width=100%></img><p></p><img src="https://stackoverflow.com/questions/66843501/Block.png" width=100%></img></img>
      </div>


   </body>
</html>

En tu código editado usando funciones jQuery pero olvidas importar el archivo js de la biblioteca jQuery

-adampweb

28/03/2021 a las 17:18

@AdánP. He importado jQuery e Isotope pero los botones siguen sin funcionar. Probé varios navegadores e intenté descargar los archivos para poder importarlos localmente.

-Moz

28/03/2021 a las 17:42

1

No vi que quisieras resolver esto con jQuery, así que se me ocurrió una solución con JavaScript básico. Déjame saber si esto funciona para ti. Tuve que darle a la imagen un índice de datos para que funcionara. Los colores de fondo son solo porque no había imágenes: codepen.io/Bertw/pen/LYxZQOd

- Bert W.

28/03/2021 a las 17:44

@marmstrong ¡fantástico! Lo pondré en una respuesta a continuación para marcar respondido o votar a favor

- Bert W.

28/03/2021 a las 18:06

@BertW Entonces, los botones funcionan y el contenido está en el espacio correcto, pero para el botón "Verde" y "Azul" ssecciones, la segunda imagen que se muestra está sesgada hacia arriba (principalmente fuera de la página). He husmeado para intentar solucionar este problema, pero la única diferencia que encontré fue el uso de " en dos casos, mientras que en todos los demás se usó solo ', lo cual corregí para lograr uniformidad y eso no tuvo ningún impacto. Todo lo demás parece ser exactamente igual entre todos ellos, así que no puedo entender por qué sólo esos dos colores tienen este problema. i.imgur.com/MMWxNNn.png

-Moz

28/03/2021 a las 20:48



------------------------------------

Solución con JavaScript:

const button = document.querySelectorAll('.navbar button');
const img = document.querySelectorAll('img');

button.forEach(btn => btn.addEventListener('click', displayCard));

function displayCard(e) {
  for (let i =0; i < button.length; i++){
    if (e.target === button[i]) {
    if (button[i].textContent === 'All') {
      for (let i = 0; i < img.length; i++){  
          img[i].style.display = 'block';
      }
    } else if (button[i].textContent === 'Red'){
      for (let i = 0; i < img.length; i++){
        if (img[i].getAttribute('data-index') ==='2'){
          img[i].style.display = 'block';
        } else {
          img[i].style.display = 'none';
        }
      }
    } else if (button[i].textContent === 'Yellow'){
      for (let i = 0; i < img.length; i++){
        if (img[i].getAttribute('data-index') ==='3'){
          img[i].style.display = 'block';
        } else {
          img[i].style.display = 'none';
        }
      } 
  } else if (button[i].textContent === 'Green'){
      for (let i = 0; i < img.length; i++){
        if (img[i].getAttribute('data-index') ==='4'){
          img[i].style.display = 'block';
        } else {
          img[i].style.display = 'none';
        }
      }
} else if (button[i].textContent === 'Blue'){
      for (let i = 0; i < img.length; i++){
        if (img[i].getAttribute('data-index') ==='5'){
          img[i].style.display = 'block';
        } else {
          img[i].style.display = 'none';
        }
      }
} else if (button[i].textContent === 'Pink'){
      for (let i = 0; i < img.length; i++){
        if (img[i].getAttribute('data-index') ==='1'){
          img[i].style.display = 'block';
        } else {
          img[i].style.display = 'none';
        }
      }
    }
    }
  }
}
img{
  height: 400px;
  width: 300px;
}
img[src="https://stackoverflow.com/questions/66843501/Block2.png"]{
  background-color: red;
}
img[src="https://stackoverflow.com/questions/66843501/Block3.png"]{
  background-color: yellow;
}
img[src="https://stackoverflow.com/questions/66843501/Block4.png"]{
  background-color: green;
}
img[src="https://stackoverflow.com/questions/66843501/Block5.png"]{
  background-color: blue;
}
img[src="https://stackoverflow.com/questions/66843501/Block.png"]{
  background-color: pink;
}
   <head>
      <meta charset="UTF-8">
      <title>Mozart Armstrong Portfolio Graphic Design</title>
         <style>

            @font-face {
              font-family: Klik;
              src: url(klik-light-webfont.woff);
            }

            @font-face {
              font-family: theBoldFont;
              src: url(theboldfont.ttf);
            }

            .main {
              margin-left: 200px;
              padding: 105px 10px;
              font-size: 16px;
              font-family: CaviarDreams;
              color: #000000;
              display: block;
              column-count: 3;
              column-width: 32%
              column-gap: 1%;
            }

            .main p {
              font-size: 24px;
              font-family: CaviarDreams;
              color: #000000;
            }
            
            .sidebar {
              height: 100%;
              width: 200px;
              position: fixed;
              z-index: 3;
              top: 0;
              left: 0;
              background-color: #000000;
              overflow-x: hidden;
              padding-top: 20px;
            }

            .sidebar a {
              padding: 6px 8px 6px 16px;
              text-decoration: none;
              font-size: 16px;
              font-family: CaviarDreams;
              color: #ffffff;
              display: block;
            }

            .sidebar a:hover {
              color: #808080;
            }

            .sidebar b {
              padding: 6px 8px 6px 16px;
              text-decoration: none;
              font-family: theBoldFont;
              font-size: 28px;
              color: #ffffff;
              display: block;
            }

            .sidebar c {
              padding: 6px 8px 6px 16px;
              text-decoration: none;
              font-size: 13px;
              font-family: Klik;
              color: #ffffff;
              display: block;
            }

            .navbar {
              position: absolute;
              padding: 10px 0px 10px 10px;
              height: 100px;
              width: 100%;
              right: 0;
              top: 0;
              z-index: 2;
              overflow-x: hidden;
              background-color: #808080;
            }

            .navbar a {
              padding: 20px 8px 16px 16px;
              text-decoration: none;
              font-size: 16px;
              font-family: Klik;
              color: #ffffff;
            }

            .navbar b {
              padding: 0px 0px 0px 0px;
              width: 225px;
              text-decoration: none;
              font-size: 16px;
              font-family: Klik;
              color: #ffffff;
              display: inline-block;
            }

            .navbar c {
              padding: 25px 225px 0px 245px;
              width: 100%;
              height: 30px;
              text-decoration: none;
              font-size: 26px;
              font-family: theBoldFont;
              color: #000000;
              display: inline-block;
            }

            .navbar button {
              background-color: #000000;
              border: none;
              color: #ffffff;
              padding: 10px 32px;
              text-align: center;
              text-decoration: none;
              display: inline-block;
              font-size: 16px;
              font-family: Klik;
            }

            .navbar button:hover {
              background-color: #ffffff;
              border: none;
              color: #000000;
              padding: 10px 32px;
              text-align: center;
              text-decoration: none;
              display: inline-block;
              font-size: 16px;
              font-family: Klik;
            }

            
         </style>
   </head>
   <body>
      <div class="sidebar">
         <b>Mozart</b>
         <b>Armstrong</b>
         <c>design • marketing • branding</c>
         <b></b>
         <b></b>
         <b></b>
         <a href="">Graphic Design</a>
         <a href="">Illustration</a>
         <a href="">Animations</a>
         <a href="">Photography</a>
         <a href="">Writing</a>
         <a href="">Fashion Design</a>
         <b></b>
         <b></b>
         <a href="">About</a>
      </div>
       <div class="navbar">
         <c>Graphic Design</c>
         <b></b>
         <button>All</button>
         <button>Red</button>
         <button>Yellow</button>
         <button>Green</button>
         <button>Blue</button>
         <button>Pink</button>
       </div>
      <div class="main">
        <p></p><img src="https://stackoverflow.com/questions/66843501/Block2.png" data-index='2' width=100%></img><p></p><img src="https://stackoverflow.com/questions/66843501/Block.png" data-index="1" width=100%></img><p></p><img src="https://stackoverflow.com/questions/66843501/Block3.png" data-index='3' width=100%></img><nextcol>
        <p></p><img src="https://stackoverflow.com/questions/66843501/Block4.png" data-index="4" width=100%></img><p></p><img src="https://stackoverflow.com/questions/66843501/Block.png" data-index='1' width=100%></img><p></p><img src="https://stackoverflow.com/questions/66843501/Block2.png" data-index='2' width=100%></img><nextcol>
        <p></p><img src="https://stackoverflow.com/questions/66843501/Block5.png" data-index='5' width=100%><p></p><img src="https://stackoverflow.com/questions/66843501/Block3.png" data-index='3' width=100%></img><p></p><img data-index='1' src="https://stackoverflow.com/questions/66843501/Block.png" width=100%></img></img>
      </div>


   </body>
</html>



------------------------------------

Esto se puede hacer fácilmente, por ejemplo, con la biblioteca Isotope jQuery:

// external js: isotope.pkgd.js


        // init Isotope
        var $grid = $('.main').isotope({
          itemSelector: '.img-block',
          layoutMode: 'fitRows'
        });

        // bind filter button click
        $('#filters').on( 'click', 'button', function() {
          var filterValue = $( this ).attr('data-filter');
          $grid.isotope({ filter: filterValue });
        });

        // change is-checked class on buttons
        $('.button-group').each( function( i, buttonGroup ) {
          var $buttonGroup = $( buttonGroup );
          $buttonGroup.on( 'click', 'button', function() {
            $buttonGroup.find('.is-checked').removeClass('is-checked');
            $( this ).addClass('is-checked');
          });
        });
@font-face {
      font-family: Klik;
      src: url(klik-light-webfont.woff);
    }

    @font-face {
      font-family: theBoldFont;
      src: url(theboldfont.ttf);
    }
    body{
      padding: 0;
      margin: 0;
    }

    .main {
      margin-left: 200px;
      padding: 105px 10px;
      font-size: 16px;
      font-family: CaviarDreams;
      color: #000000;
      display: block;
      column-count: 3;
      column-width: 32%
      column-gap: 1%;
    }

    .main p {
      font-size: 24px;
      font-family: CaviarDreams;
      color: #000000;
    }

    .sidebar {
      height: 100%;
      width: 200px;
      position: fixed;
      z-index: 3;
      top: 0;
      left: 0;
      background-color: #000000;
      overflow-x: hidden;
      padding-top: 20px;
    }

    .sidebar a {
      padding: 6px 8px 6px 16px;
      text-decoration: none;
      font-size: 16px;
      font-family: CaviarDreams;
      color: #ffffff;
      display: block;
    }

    .sidebar a:hover {
      color: #808080;
    }

    .sidebar b {
      padding: 6px 8px 6px 16px;
      text-decoration: none;
      font-family: theBoldFont;
      font-size: 28px;
      color: #ffffff;
      display: block;
    }

    .sidebar c {
      padding: 6px 8px 6px 16px;
      text-decoration: none;
      font-size: 13px;
      font-family: Klik;
      color: #ffffff;
      display: block;
    }

    .navbar {
    padding: 10px 0px 10px 10px;
    right: 0;
    margin-left: 200px;
    top: 0;
    z-index: 2;
    overflow-x: hidden;
    background-color: #808080;
    }

    .navbar a {
      padding: 20px 8px 16px 16px;
      text-decoration: none;
      font-size: 16px;
      font-family: Klik;
      color: #ffffff;
    }

    .navbar b {
      padding: 0px 0px 0px 0px;
      width: 225px;
      text-decoration: none;
      font-size: 16px;
      font-family: Klik;
      color: #ffffff;
      display: inline-block;
    }

    .navbar c {
      padding: 25px 225px 0px 245px;
      width: 100%;
      height: 30px;
      text-decoration: none;
      font-size: 26px;
      font-family: theBoldFont;
      color: #000000;
      display: inline-block;
    }

    .navbar button {
      background-color: #000000;
      border: none;
      color: #ffffff;
      padding: 10px 32px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
      font-family: Klik;
    }

    .navbar button:hover {
      background-color: #ffffff;
      border: none;
      color: #000000;
      padding: 10px 32px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
      font-family: Klik;
    }
    .img-block{
      margin: 10px;
    }
<!DOCTYPE html>
<head>
  <meta charset="UTF-8">
  <title>Mozart Armstrong Portfolio Graphic Design</title>
</head>
<body>
<div class="sidebar">
   <b>Mozart</b>
   <b>Armstrong</b>
   <c>design • marketing • branding</c>
   <b></b>
   <b></b>
   <b></b>
   <a href="">Graphic Design</a>
   <a href="">Illustration</a>
   <a href="">Animations</a>
   <a href="">Photography</a>
   <a href="">Writing</a>
   <a href="">Fashion Design</a>
   <b></b>
   <b></b>
   <a href="">About</a>
 </div>
 <div class="navbar">
   <c>Graphic Design</c>
   <b></b>
   <div id="filters" class="button-group">
     <button data-filter="*">All</button>
     <button data-filter=".img-red">Red</button>
     <button data-filter=".img-yellow">Yellow</button>
     <button data-filter=".img-green">Green</button>
     <button data-filter=".img-blue">Blue</button>
     <button data-filter=".img-pink">Pink</button>
   </div>
 </div>
 <div class="main">
  <div class="img-block img-red" >
    <img src="https://dummyimage.com/300x400/ff0000/fff" width="100%" />
  </div>

  <div class="img-block img-yellow">
    <img src="https://dummyimage.com/300x400/ffff00/000000" width="100%" />
  </div>

  <div class="img-block img-green">
    <img src="https://dummyimage.com/300x400/25b825/000000" width="100%" />
  </div>

  <div class="img-block img-blue">
    <img src="https://dummyimage.com/300x400/2a31eb/ffffff" width="100%" />
  </div>

  <div class="img-block img-pink">
    <img src="https://dummyimage.com/300x400/db2aeb/ffffff" width="100%" />
  </div>

  <div class="img-block img-green">
    <img src="https://dummyimage.com/300x400/25b825/000000" width="100%" />
  </div>

  <div class="img-block img-green">
    <img src="https://dummyimage.com/300x400/25b825/000000" width="100%" />
  </div>

  <div class="img-block img-red">
    <img src="https://dummyimage.com/300x400/ff0000/fff" width="100%" />
  </div>

  <div class="img-block img-red">
    <img src="https://dummyimage.com/300x400/ff0000/fff" width="100%" />
  </div>

  <div class="img-block img-yellow">
    <img src="https://dummyimage.com/300x400/ffff00/000000" width="100%" />
  </div>

  <div class="img-block img-yellow">
    <img src="https://dummyimage.com/300x400/ffff00/000000" width="100%" />
  </div>

</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://npmcdn.com/isotope-layout@3/dist/isotope.pkgd.js"></script>
</body>
    </html>

2

¡Muchas gracias! Copié la respuesta del código exacto y los bloques de imágenes finalmente aparecen en el espacio correcto sin estropear el resto de la página. Sin embargo, los botones todavía no funcionan. Se puede hacer clic en ellos, pero nada cambia.

-Moz

28/03/2021 a las 17:35

Los botones funcionan tanto en esta vista de demostración como en este proyecto de Codepen

-adampweb

28/03/2021 a las 19:04

Su guía para un futuro mejor - libreflare
Su guía para un futuro mejor - libreflare