【发布时间】:2018-04-10 10:20:26
【问题描述】:
尝试将随机类添加到两个类(.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>
【问题讨论】:
-
你是如何应用随机性的?
-
你只需要两个元素(或左/右元素的倍数)?如果是这样,那么显而易见且微不足道的解决方案,如果您在研究过程中没有以一种或其他形式遇到过这个问题,那就是简单地打乱数组,然后从中取出前两个值......
-
@UncaughtTypeError 检查codepen
-
@pedram "@OP put that into the question" 是正确的回答 ;-)
-
@Rob 将第一级的
$('left')更正为$('.left')
标签: javascript jquery html css random