簡體   English   中英

如何在 JS 中制作一組按鈕? 以及如何使用此設置隨機圖像?

[英]How do I make an Array of Buttons out of this in JS? And How do I set Random Images with this?

所以我正在嘗試制作一個記憶游戲。 目前我正在嘗試隨機設置卡片的圖像,但我的代碼只是更改為頂部圖像。

var images = ["url(IMG1.jpg)","url(IMG2.jpg)"...];
var randomIMG =0;

var card = "<div class='flip-card'><div class='flip-card-inner'><div class='flip-card-front'><button id='button'onclick='Flipfront(this)'style='width:300px;height:300px; marign:50px; background-image:url(Frontpage.jpg);'></button></div><div class='flip-card-back'><button id='button2'onclick='Flipback(this)'style='width:300px;height:300px; marign:50px; background-image:images[randomIMG];background-repeat:no-repeat;background-size:contain;'></button></div></div></div>"



for (let i = 0; i < level; i++) {
    document.querySelector("#container").innerHTML +=card;
}
function RandomBG(){
    for (let i = 0; i<level;i++){
        randomIMG = Math.floor(Math.random()*9)+0;
        document.getElementById("button2").style.backgroundImage = images[randomIMG]; 
    }
}
function Flipfront(el){
            RandomBG();
             el.closest('.flip-card').classList.add('flipped');
            flipped++;

}

以及稍后,我如何將我所有的按鈕放入一個數組中?

在這一行

document.getElementById("button2").style.backgroundImage = images[randomIMG];

您正在設置button2的背景。 您需要確保獲得正確的元素:

function RandomBG(el){
    for (let i = 0; i<level;i++){
        randomIMG = Math.floor(Math.random()*9)+0;
        el.style.backgroundImage = images[randomIMG]; 
    }
}

並且你通過了它:

function Flipfront(el){
            RandomBG();
             el.closest('.flip-card').classList.add('flipped');
            flipped++;

}

如果您要做的只是獲取頁面中的所有按鈕:

let btns = document.querySelectorAll("button");

如果您想要一些特定的,請更改 css 選擇器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM