将多个.random类添加到多个div而不重复

时间:2017-10-29 08:36:10

标签: javascript jquery html css random

尝试将随机类添加到两个类(.left& .right)但是两个随机div的规则不能同时出现

JS:

$(document).ready(function(){
var classes = ['random-1','random-2', 'random-3']; //add as many classes as u want
var randomnumber = Math.floor(Math.random()*classes.length);

$('.left').addClass(classes[randomnumber]);
});

HTML:

<div class="left">
  Left
</div>

<div class="right">
  Right
</div>


.left {
  background: blue;
  height: 100vh;
  width: 50%;
  float: left;
  position: relative;
}
.right {
  background: red;
  height: 100vh;
  width: 50%;
  float: right;
}

  .random-1 {
     background: orange;
  }
  .random-2 {
     background: yellow;
  }
  .random-3 {
     background: pink;
  }
  .random-4 {
     background: green;
  }
  .random-5 {
     background: blueviolet;
  }

理想的结果将是

<div class="left random-1">
  Left
</div>

<div class="right random-4">
  Right
</div>

https://codepen.io/anon/pen/OOJaqL

2 个答案:

答案 0 :(得分:2)

您可以使用迭代的while循环,直到选择了两个随机且唯一的类。

function getRandomClass() {

    let classes = ['random-1','random-2', 'random-3'];
    let index = Math.floor(Math.random() * classes.length);

    return classes[index];
}

$(document).ready(function() {

    let leftClass = null;
    let rightClass = null;

    while (leftClass == rightClass) {
        leftClass = randomClass();
        rightClass = randomClass();
    }

    $('.left').addClass(leftClass);
    $('.right').addClass(rightClass);
});

答案 1 :(得分:0)

.random-*类添加到左侧div,仅当右侧div没有此类时。

var rightHasClass = $('.right').hasClass(classes[randomnumber]);    
if( ! rightHasClass){
    $('.left').addClass(classes[randomnumber]);
}

var leftHasClass = $('.left').hasClass(classes[randomnumber]);
if( ! leftHasClass){
    $('.right').addClass(classes[randomnumber]);
}