是否有一种方法随机应用css属性从一个列表到一堆元素

Is there a way to randomly apply css properties from a list to a bunch of elements?

本文关键字:列表 一个 一堆 元素 应用 一种 方法 随机 css 是否 属性      更新时间:2023-09-26

更确切地说,我可以应用到我的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);}
相关文章: