我需要将 6 个唯一数字 (0-5) 随机分配给 6 个类名。每个类名一个数字
如何使用它: 单击汉堡包图标时,菜单打开并显示 6 行个人姓名,每行都有特定的背景图像。 “过渡”是为了让配置文件逐步介入。
这是我目前所拥有的,但我收到了重复的数字。我希望随机分配数字,因此每次打开菜单时配置文件的顺序都不同。
var generate_random_number = function() {
var number = Math.floor(Math.random() * 6);
return number;
};
var build_menu_profiles = function() {
$(".profile-0").html("<div class='profile-title'><span class='emphasis'>Profile</span> 1</div>");
$(".profile-1").html("<div class='profile-title'><span class='emphasis'>Profile</span> 2</div>");
$(".profile-2").html("<div class='profile-title'><span class='emphasis'>Profile</span> 3</div>");
$(".profile-3").html("<div class='profile-title'><span class='emphasis'>Profile</span> 4</div>");
$(".profile-4").html("<div class='profile-title'><span class='emphasis'>Profile</span> 5</div>");
$(".profile-5").html("<div class='profile-title'><span class='emphasis'>Profile</span> 6</div>");
};
var animate_menu_profiles = function(i) {
i = 0;
$(".profiles").each(function(i) {
$(this).toggleClass("transition-" + i);
$(this).toggleClass("profile-" + generate_random_number());
build_menu_profiles();
});
};
最佳答案
您并不想生成随机数,而是想随机排列一组已知的六个数字。这是一种方法:
var indices = [0,1,2,3,4,5].sort(function(a,b) { return Math.random()-0.5; });
// produces [3,1,5,4,0,2] or whatever
然后您可以在循环中使用它,如下所示:
$(".profiles").each(function(i) {
$(this).toggleClass("transition-" + i);
$(this).toggleClass("profile-" + indices[i]);
...
请注意,像那样一起使用 .sort()
和 Math.random()
是一种 hack,但就您的目的而言,它应该可以正常工作。
但是,您现有的.each()
循环无法完成这项工作。当前,当它处理每个元素时,它使用 .toggle()
,这意味着如果该元素已经具有 profile-x
类名,它将被删除,否则将被添加.将其与随机化放在一起,一些元素最终将没有 profile-x
类,而一些元素最终将有多个。
在我看来,最简单的方法是实际移动元素而不是更改它们的类。我假设它们有一个共同的父级 class="profile-container"
:
var animate_menu_profiles = function(i) {
var $profileContainer = $(".profile-container");
var $profiles = $(".profiles");
$profiles.sort(function(a,b) { return Math.random()-0.5; });
$profiles.each(function(i){
$(this)
.toggleClass("transition-" + i)
.appendTo($profileContainer);
});
build_menu_profiles();
};
关于JavaScript — 为每个类名随机分配 8 个唯一数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37636323/