简体   繁体   中英

The js changing backgrounds function isn't working

Imma trying to create a simple function that change the background of a specific element when the user clicks it


const chrollofunction = document.querySelectorAll("article .krolor");

const randomclickfunctionkro = function() {

    const backgrounds = new Array();
    backgrounds[0] = new Image();
    backgrounds[0].src = 'pics/اليكيورا.jpg';

    backgrounds[1] = new Image();
    backgrounds[1].src = 'pics/pain.jpg';

    backgrounds[2] = new Image();
    backgrounds[2].src = 'pics/قزم2.jpg';

    const randomindex = Math.floor(Math.random() * backgrounds.length);

    const randombg = backgrounds[randomindex];
    
    chrollofunction.style.backgroundColor = randombg;
    console.log('The user clicked and changed the color to ' + randombg);

};

chrollofunction.onclick = randomclickfunctionkro;

So i guess that there was a problem with the backgrounds function array, But i can't really understand it and I looked for how it should be written and the correct syntax but can't find any problem really

You can change the background image of an element like so:

 chrollofunction.style.backgroundImage = `url(${randombg.src})`;

You may also need to add a few styles to make the image fit the container:

chrollofunction.style.backgroundSize = "contain";
chrollofunction.style.backgroundRepeat = "no-repeat";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM