AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79377649
Accepted
lharby
lharby
Asked: 2025-01-22 20:08:27 +0800 CST2025-01-22 20:08:27 +0800 CST 2025-01-22 20:08:27 +0800 CST

O JavaScript embaralha elementos, mas rastreia o índice original ou usa o módulo para inseri-los na marcação pai

  • 772

Tenho a seguinte marcação:

<div class="">
  <div class="tiled-gallery__gallery">
    <div class="tiled-gallery__row columns-1">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-dan/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-dan-1024x1024.jpeg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
    </div>
    <div class="tiled-gallery__row columns-2">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-jessica/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-jessica-1024x1024.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-jessica-1024x1024.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-jessica-1024x1024.jpg?resize=1132%2C1132&amp;strip=info&amp;ssl=1 1132w"
            />
          </a>
        </figure>
      </div>
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/rebecca-2/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/Rebecca-1-1024x1024.jpg?resize=1333%2C1333&amp;strip=info&amp;ssl=1 1333w"
            />
          </a>
        </figure>
      </div>
    </div>
    <div class="tiled-gallery__row columns-2">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-2/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-2-1024x768.jpeg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-4/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-4-733x1024.jpeg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
    </div>
    <div class="tiled-gallery__row columns-2">
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-teram-test-3/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-teram-test-3-1024x718.jpg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
      <div class="tiled-gallery__col">
        <figure class="tiled-gallery__item">
          <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-1/">
            <img
              srcset="https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=600%2C600&amp;strip=info&amp;ssl=1 600w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=900%2C900&amp;strip=info&amp;ssl=1 900w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=1200%2C1200&amp;strip=info&amp;ssl=1 1200w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=1500%2C1500&amp;strip=info&amp;ssl=1 1500w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=1800%2C1800&amp;strip=info&amp;ssl=1 1800w,https://i0.wp.com/staging-7578-youthlandscapers.wpcomstaging.com/wp-content/uploads/2024/12/our-team-test-1-768x1024.jpg?resize=2000%2C2000&amp;strip=info&amp;ssl=1 2000w"
            />
          </a>
        </figure>
      </div>
    </div>
  </div>
</div>

Quero poder embaralhar cada item: <div class="tiled-gallery__item">em uma posição aleatória, porém o problema que tenho é que o primeiro item tem um contêiner pai que especifica 1 coluna, columns-1embora a maior parte da marcação use a classe de layout de 2 colunas columns-2.

Eu escrevi um shuffle básico usando este javascript:

const shuffleElems = () => {
  const wrapper = document.querySelector(".tiled-gallery__gallery");
  const items = wrapper.querySelectorAll(
    ".tiled-gallery__row .tiled-gallery__col"
  );

  for (var i = items.length; i >= 0; i--) {
    wrapper.appendChild(items[(Math.random() * i) | 0]);
  }
};

shuffleElems();

Isso funciona porque reorganiza os itens, mas poderia adicionar um único item em uma coluna que deveria levar dois. Então, presumo que preciso de alguma forma de rastrear o índice original e o novo, e usar um módulo ou verificar a classe pai. Ou possivelmente embaralhar tudo nas classes da coluna 2 e então apenas trocar a única linha no final?

Espero que isso faça sentido, todo o código está em codesandbox .

Adicionarei uma captura de tela em breve.

javascript
  • 1 1 respostas
  • 34 Views

1 respostas

  • Voted
  1. Best Answer
    C3roe
    2025-01-22T21:06:36+08:002025-01-22T21:06:36+08:00

    no entanto, o problema que tenho é que o primeiro item tem um contêiner pai que especifica 1 coluna columns-1, embora a maior parte da marcação use a classe de layout de 2 colunas columns-2.

    Já que essa estrutura é o problema aqui, vamos ignorá-la então :-)

    Pegue os itens da sua galeria, converta-os em uma matriz e embaralhe-os.

    Em seguida, faça um loop nas colunas e simplesmente adicione um item da matriz embaralhada a cada uma delas.

    (Substituí as imagens por números simples em forma de texto aqui e adicionei um contorno aos .tiled-gallery__rowelementos para que possamos ver facilmente os itens sendo embaralhados, mas permanecendo dentro da estrutura fornecida.)

    let items = [...document.querySelectorAll('.tiled-gallery__gallery .tiled-gallery__item')];
    shuffleArray(items);
    
    document.querySelectorAll('.tiled-gallery__gallery .tiled-gallery__col').forEach(function(parent, index) {
       parent.appendChild(items[index]);
    });
    
    
    // array shuffle function grabbed from the internet, feel free to replace with your own
    function shuffleArray(array) {
        for (let i = array.length - 1; i >= 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
    }
    .tiled-gallery__row { outline: 1px solid blue; }
    <div class="">
      <div class="tiled-gallery__gallery">
        <div class="tiled-gallery__row columns-1">
          <div class="tiled-gallery__col">
            <figure class="tiled-gallery__item">
              <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-dan/">
                1
              </a>
            </figure>
          </div>
        </div>
        <div class="tiled-gallery__row columns-2">
          <div class="tiled-gallery__col">
            <figure class="tiled-gallery__item">
              <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-jessica/">
                2
              </a>
            </figure>
          </div>
          <div class="tiled-gallery__col">
            <figure class="tiled-gallery__item">
              <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/rebecca-2/">
                3
              </a>
            </figure>
          </div>
        </div>
        <div class="tiled-gallery__row columns-2">
          <div class="tiled-gallery__col">
            <figure class="tiled-gallery__item">
              <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-2/">
                4
              </a>
            </figure>
          </div>
          <div class="tiled-gallery__col">
            <figure class="tiled-gallery__item">
              <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-4/">
                5
              </a>
            </figure>
          </div>
        </div>
        <div class="tiled-gallery__row columns-2">
          <div class="tiled-gallery__col">
            <figure class="tiled-gallery__item">
              <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-teram-test-3/">
                6
              </a>
            </figure>
          </div>
          <div class="tiled-gallery__col">
            <figure class="tiled-gallery__item">
              <a href="https://staging-7578-youthlandscapers.wpcomstaging.com/2024/12/11/our-team/our-team-test-1/">
                7
              </a>
            </figure>
          </div>
        </div>
      </div>
    </div>

    • 2

relate perguntas

  • classificação de mesclagem não está funcionando - código Javascript: não é possível encontrar o erro mesmo após a depuração

  • método select.remove() funciona estranho [fechado]

  • Sempre um 401 res em useOpenWeather () - react-open-weather lib [duplicado]

  • O elemento de entrada não possui atributo somente leitura, mas os campos ainda não podem ser editados [fechado]

  • Como editar o raio do primeiro nó de um RadialTree D3.js?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve