javascript js更改背景功能不起作用

mspsb9vt  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(250)

我试着创建一个简单的函数,当用户点击某个特定元素时,它会改变该元素的背景

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;

所以我猜后台函数数组有问题,但我不能真正理解它,我寻找它应该如何编写和正确的语法,但不能找到任何问题真的

ukxgm1gy

ukxgm1gy1#

可以按如下方式更改元素的背景图像:

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

您可能还需要添加一些样式以使图像适合容器:

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

相关问题