【问题标题】:How to randomize the position of divs如何随机化div的位置
【发布时间】:2021-11-11 06:42:22
【问题描述】:

也许这是一个愚蠢的问题,但我无法解决这个问题。基本上我需要的是随机化项目的位置,即项目 1 采用项目 3(或 2 或 4)的样式,项目 2 采用 1、3、4 的样式,依此类推。

这是我的代码

let item = document.querySelectorAll('.item')

for (let i = 0; i < item.length; i++) {
  const getRight = item[i].style.right
  const getTop = item[i].style.top
  const getStyles = [getRight, getTop]
  console.log(`Item${i}, Style: ${getStyles}`);
}
.items--cloud {
  position: relative;
  height: 400px;
  width: 500px;
  background: #333;
}

[data-item] {
  position: absolute;
  transform: translate3d(var(--x), var(--y), 0);
}
<div class="items--cloud">
  <div data-item="item-1" class="item item-1" style="right: 0%;top: 40%;">
    <img src="https://via.placeholder.com/90x90.?text=item1" alt="">
  </div>
  <div data-item="item-2" class="item item-2" style="right: 53%;top: 28%;">
    <img src="https://via.placeholder.com/90x90?text=item2" alt="">
  </div>
  <div data-item="item-3" class="item item-3" style="right: 39%;top: 4%;">
    <img src="https://via.placeholder.com/90x90?text=item3" alt="">
  </div>
  <div data-item="item-4" class="item item-4" style="right: 79%;top: 26%;">
    <img src="https://via.placeholder.com/90x90?text=item4" alt="">
  </div>
</div>

如果有必要,我使用 jQuery 没有问题。

【问题讨论】:

  • 也许这会有所帮助:stackoverflow.com/questions/7186644/…
  • 我不完全确定你对Basically what I need is to randomize the position of the items, i.e. item 1 takes the style of item 3 (or 2 or 4), item 2 takes the style of 1,3,4 and so on. 的意思所以位置集是固定的,但你想洗牌你的哪些元素具有该集的哪个位置,但没有一个元素应该和那个集合的位置一样吗?
  • @t.niese 嗯,这很理想,但如果一个元素不改变它的位置,那也不是问题。

标签: javascript arrays sorting random


【解决方案1】:

一种方法是为您要使用的每个位置创建一个 css 规则。

为每个元素分配一个初始位置(确保每个元素都有不同的位置类)

在洗牌时,您收集应用的位置,将它们从元素中移除,洗牌位置数组并重新应用它们。

shuffleArray 数组函数取自 answer to "How to randomize (shuffle) a JavaScript array?"

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]];
    }
}

function shuffelPositions() {
  let items = document.querySelectorAll('.item')
  
  // collect the positions the elements have right now and remove the current one
  let positions = Array.from(items).map( item => {
    // iterat over item.classLis and search for the class starting with `position-`
    let positionClass = Array.from(item.classList).find(item => item.match(/^position-/))
    // remove the found class
    item.classList.remove(positionClass)

    //return it to let the `.map` create the new array containing that class
    return positionClass
  })
  
  // shuffel those positions
  shuffleArray(positions)
  
  // apply the shuffled positions
  for (let i = 0; i < items.length; i++) {
    items[i].classList.add(positions[i])
  }
}

document.getElementById('shuffle').addEventListener('click', shuffelPositions)
.items--cloud {
  position: relative;
  height: 400px;
  width: 500px;
  background: #333;
}

[data-item] {
  position: absolute;
  transform: translate3d(var(--x), var(--y), 0);
}

.position-1 {
  right: 0%; top: 40%;
}

.position-2 {
  right: 53%;top: 28%;
}

.position-3 {
  right: 39%;top: 4%;
}

.position-4 {
  right: 79%;top: 26%;
}
<div class="items--cloud">
  <div data-item="item-1" class="item item-1 position-1">
    <img src="https://via.placeholder.com/90x90.?text=item1" alt="">
  </div>
  <div data-item="item-2" class="item item-2 position-2">
    <img src="https://via.placeholder.com/90x90?text=item2" alt="">
  </div>
  <div data-item="item-3" class="item item-3 position-3">
    <img src="https://via.placeholder.com/90x90?text=item3" alt="">
  </div>
  <div data-item="item-4" class="item item-4 position-4">
    <img src="https://via.placeholder.com/90x90?text=item4" alt="">
  </div>
</div>

<button id="shuffle">shuffle positions</button>

如果你不想使用类,你可以使用 data 属性,这样做的好处是你可以赋予它更多的语义含义,如果你需要的话可以更容易地检索使用的位置:

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]];
    }
}

function shuffelPositions() {
  let items = document.querySelectorAll('.item')
  
  // collect the positions the elements have right now and remove the current one
  let positions = Array.from(items).map( item => {
    return item.dataset.position;
  })
  
  // shuffel those positions
  shuffleArray(positions)
  
  // apply the shuffled positions
  for (let i = 0; i < items.length; i++) {
    items[i].dataset.position = positions[i]
  }
}

document.getElementById('shuffle').addEventListener('click', shuffelPositions)
.items--cloud {
  position: relative;
  height: 400px;
  width: 500px;
  background: #333;
}

[data-item] {
  position: absolute;
  transform: translate3d(var(--x), var(--y), 0);
}

[data-position="1"] {
  right: 0%; top: 40%;
}

[data-position="2"]{
  right: 53%;top: 28%;
}

[data-position="3"]{
  right: 39%;top: 4%;
}

[data-position="4"] {
  right: 79%;top: 26%;
}
<div class="items--cloud">
  <div data-item="item-1" class="item item-1" data-position="1">
    <img src="https://via.placeholder.com/90x90.?text=item1" alt="">
  </div>
  <div data-item="item-2" class="item item-2" data-position="2">
    <img src="https://via.placeholder.com/90x90?text=item2" alt="">
  </div>
  <div data-item="item-3" class="item item-3" data-position="3">
    <img src="https://via.placeholder.com/90x90?text=item3" alt="">
  </div>
  <div data-item="item-4" class="item item-4" data-position="4">
    <img src="https://via.placeholder.com/90x90?text=item4" alt="">
  </div>
</div>

<button id="shuffle">shuffle positions</button>

【讨论】:

  • @JamalDols 我用第二种解决方案更新了我的答案,根据用例可能会更好。
【解决方案2】:

rando.js 提供了一个 randoSequence 函数,让这变得非常简单

function swapStyles(elements, styles){
    if(elements.length < 2) return false;
    
    var randomElements = randoSequence(elements).slice(-2).map((i) => i.value), temp = "";
    for(var i = 0; i < styles.length; i++){
        temp = randomElements[0].style[styles[i]];
        randomElements[0].style[styles[i]] = randomElements[1].style[styles[i]];
        randomElements[1].style[styles[i]] = temp;
    }
}
.abs{
  position:absolute;
  width:100px;
  height:50px;
}
<script src="https://randojs.com/2.0.0.js"></script>

<button onclick="swapStyles(document.getElementsByClassName('abs'), ['top', 'right']);">CLICK TO SWAP!</button>
<div class="abs" style="top:10px;right:10px;background:red;"></div>
<div class="abs" style="top:60px;right:120px;background:blue;"></div>
<div class="abs" style="top:120px;right:330px;background:green;"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多