-1

更确切地说,我可以应用到我拥有的 20 个 div、10 个背景图像,所以有两个具有相同背景的元素吗?
我想重现一个游戏,但我没有开始,因为我不知道这是否可能。我有 20 张牌面朝下。当我单击一个时,它们会翻转并显示它们的图像。但它们是成对的。因此,当您单击第二个并且它们的图像不匹配时,它们会翻转回来。所以你必须牢记他们的位置,直到你匹配他们。如果您第一次翻转而第二次翻转具有相同的背景图像,则它们仍然面朝上。但现在我只想知道这种应用 css 的方式是否可行。想法是在每次重新加载时在不同位置放置背景图像。

4

2 回答 2

1

是的。

创建一个包含 10 个项目的数组,每个项目对应一个背景图像。

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 分配给backgroundImage您的每个 div 的属性,并在执行过程中删除 URL 的实例tempArray

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)
    }
}

希望这样的事情会做你需要的。

于 2013-01-09T14:14:47.487 回答
0

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);}
于 2013-01-09T14:18:13.217 回答