感谢这里的一些用户,我有一些 jQuery,可以让我随机将类名附加到我的 div 中。我对它进行了轻微的修改,这样当我单击单独的 div 时它就可以工作了。我现在遇到的唯一问题是,当我单击它时,它会不断将随机 div 附加到我的 .hexagon div 中。我真正想要它做的是将其删除并从随机列表中选择另一个。这是我所拥有的:
$(".click").click(function() {
var randomColors = ["ful","reg","emp"];
$(".hexagon").each(function(index) {
var len = randomColors.length;
var randomNum = Math.floor(Math.random()*len);
$(this).addClass(randomColors[randomNum]);
});
});
so .click 将 ful reg 或 emp 添加到我的 .hexagon div 中,但我假设因为 emp 位于我的 CSS 表中的最后,所以我的所有 div 最终都采用该样式。我希望当我单击按钮时它可以将它们交换出来。有人能帮助我吗?
这是一个 jsfiddle - http://jsfiddle.net/fv6zqu3t/
最佳答案
在添加新的随机类之前,您需要删除 3 个随机类
$(".click").click(function() {
var randomColors = ["ful","reg","emp"];
$(".hexagon").each(function(index) {
var len = randomColors.length;
var randomNum = Math.floor(Math.random()*len);
$(this).removeClass(randomColors.join(" ")).addClass(randomColors[randomNum]);
});
});
.click {
font-family: Arial;
font-weight: bold;
position: fixed;
padding: 10px;
background-color: #FFF;
margin: 10px;
z-index: 10;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.click:active {
background-color: #E8D1D1;
}
.hexagon {
position: relative;
width: 50px;
height: 28.87px;
margin: 14.43px 0;
background-color: #BF7C2A;
}
.hexagon:before,
.hexagon:after {
content: "";
position: absolute;
width: 0;
border-left: 25px solid transparent;
border-right: 25px solid transparent;
}
.hexagon:before {
bottom: 100%;
border-bottom: 14.43px solid #BF7C2A;
}
.hexagon:after {
top: 100%;
border-top: 14.43px solid #BF7C2A;
width: 0;
}
.ful {
background-color: #F2B33D;
}
.ful:before {
border-bottom: 14.43px solid #F2B33D;
}
.ful:after {
border-top: 14.43px solid #F2B33D;
}
.reg {
background-color: #BF7C2A;
}
.reg:before {
border-bottom: 14.43px solid #BF7C2A;
}
.reg:after {
border-top: 14.43px solid #BF7C2A;
}
.emp {
background-color: #403221;
}
.emp:before {
border-bottom: 14.43px solid #403221;
}
.emp:after {
border-top: 14.43px solid #403221;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="click">RANDOMISE</span>
<div class="hexagon"></div>
<div class="hexagon"></div>
<div class="hexagon"></div>
<div class="hexagon"></div>
<div class="hexagon"></div>
<div class="hexagon"></div>
<div class="hexagon"></div>
<div class="hexagon"></div>
<div class="hexagon"></div>
<div class="hexagon"></div>
$(this).removeClass(randomColors.join(""))
这将尝试删除您在 randomColors 数组中列出的任何类,然后您就可以安全地添加新的类类。
您的假设是正确的,emp
是最后一个类,因此您的样式将显示出高于其他类的样式,但这不是问题
关于javascript - 为什么我的点击函数不断添加CSS表中的最后一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26638924/