是否有一种方法随机应用css属性从一个列表到一堆元素
Is there a way to randomly apply css properties from a list to a bunch of elements?
更确切地说,我可以应用到我的20div, 10个背景图像,我有,所以有两个元素具有相同的背景?
我想复制一款游戏,但我没有开始,因为我不知道这是否可行。我有20张牌面朝上。当我点击一个,他们翻转并显示他们的图像。但它们是成对的。所以当你点击第二个,它们的图像不匹配时,它们会翻回去。所以你必须记住它们的位置,直到你匹配它们。如果你第一次翻转和第二次翻转的背景图像相同,它们仍然是正面朝上的。但是现在我只想知道这种应用css的方式是否可行。这个想法是在每次重新加载时在不同的位置有背景图像。
可以。
创建一个包含10个条目的数组,每个条目对应一个background-images。
var bg_array = [
'img01.jpg', //replace property here with URL of your image
// ... repeat
'img10.jpg'
];
接下来,创建一个带有循环的数组,该数组将包含您想要的所有实际背景图像,即在本例中为20或10对。
var i = bg_array.length,
tempArray = [];
while (i) {
i -= 1;
tempArray.push(bg_array[i]); // first instance
tempArray.push(bg_array[i]); // second instance... makes a pair
}
然后循环遍历div并从该数组中随机选择将URL分配给每个div的backgroundImage
属性,并在执行时从tempArray
中删除URL实例。
var divs = document.getElementsByTagName('div'), // this will capture all divs on the page; you might want to be more specific
d,
r;
for (d in divs) { // assume the variable divs is a collection of all your divs
r = Math.floor(Math.random() * tempArray.length); // randomly select number based on size of array
if (divs[d].style) { // check the div has a style to change!
d.style.backgroundImage = 'url("' + tempArray[r] + '")'; // apply randomly selected background image
tempArray.splice(r, 1); // remove image URL from tempArray so this won't be used again (remembering tempArray has 2 of each)
}
}
html代码应该是:
<div id="1" class="b1"></div>
<div id="2" class="b1"></div>
<div id="3" class="b2"></div>
<div id="4" class="b2"></div>
<div id="5" class="b3"></div>
<div id="6" class="b3"></div>
<div id="7" class="b4"></div>
<div id="8" class="b4"></div>
<div id="9" class="b5"></div>
<div id="10" class="b5"></div>
和css:
.b1{background:url(image1.png);}
.b2{background:url(image2.png);}
.b3{background:url(image3.png);}
.b4{background:url(image4.png);}
.b5{background:url(image5.png);}
相关文章:
- 从javascript创建一个列表
- 将jsp文件下拉列表中的选定项分配给一个java变量(比如String selection)
- 从HTTPGET返回一个自定义对象列表,以便在Angular 2应用程序中使用
- 当在Ember中点击一个项目时,我如何将一个活动类添加到项目列表中
- 如何在用户返回和上一个按钮时刷新下拉列表
- jQuery-将列表项的一个元素移动到同一项的另一个元素中+对我的列表中的每个项执行此操作
- 如何为下拉列表的每个选项添加一个属性
- 在下拉列表中选择一个选项的值
- 在Twitter BootStrap嵌套下拉列表中托管一个选择列表(IE 9特定)
- 使用jquery从列表项中移除类,并将一个类添加到另一个列表项中
- 我在下拉列表中尝试了下一个和前五年的html代码.接下来的5年我都过得很好.我怎样才能拿到之前的5年
- 我想在我的准备列表项上创建一个按钮
- 如何使用jquery将所选项目从一个下拉组列表(optgroup)移动到另一个下拉列表(optgroup)
- 我创建了一个Javascript待办事项列表,但想知道如何在浏览器刷新后保留这些帖子
- 如何将一个类一个接一个地添加到列表中的每个元素中
- JSON编码一个HTML列表——所有子项都显示在所有父项上
- 什么'是从对象列表中一次编辑一个对象的正确Angular/Firebase方法
- 我需要使用什么语法来向一个对象的成员添加一个临时数组,该成员等同于一个字符串的通用列表
- 如何强制用户从下拉列表和按钮中选择一个值以启用保存按钮
- 在另一个下拉列表中的选择上切换下拉列表中选项的可见性