如何使用 javascript 设置背景图像

how to set backgroundImage with javascript

function myFunction2() {
  for (let i=1; i < 3; i++){
    if (i<2){
      var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
      var hex1 = '#' + numhex.slice(0, 6);
      // return hex1;
      // console.log(hex1);
    }
    else {
      var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
      var hex2 = '#' + numhex.slice(0, 6);
      // return hex2;
      // console.log(hex2);
    }
    
  }
  // document.getElementById("container").style.backgroundImage = "linear-gradient(to right, " + {hex1} + ", " + {hex2} + ")";
  document.getElementById("container").setProperty("background-image", "linear-gradient(to right, " + {hex1} + ", " + {hex2});
  document.getElementById("description").innerHTML = "The code of the color is: linear-gradient( 270deg, " + hex1 + ", " + hex2 + " );";
};

Hello, I am trying to set two colors for linear-gradient as parameters inside a specific element's background-image property, but it seems that something is wrong with my setProperty. Everything is working fine except this line of code. I've also tried it with style.backgroundImage with no result. I am new to js. Thanks in advance

首先,这里有一个提示:永远不要使用 'var',而是使用 'let'。 JS中没有setProperty()的功能,需要使用element.style["style you want to change"] = "what you want to change it to"。 而且,你不应该将变量包装在'{}'中,否则它们就不是变量,所以代码应该是:

function myFunction2() {
  for (let i=1; i < 3; i++){
    if (i<2){
      var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
      var hex1 = '#' + numhex.slice(0, 6);
      // return hex1;
      // console.log(hex1);
    }
    else {
      var numhex = (Math.random() * 0xfffff * 1000000).toString(16);
      var hex2 = '#' + numhex.slice(0, 6);
      // return hex2;
      // console.log(hex2);
    }
    
  }
  document.getElementById("container").style["background-image"] = "linear-gradient(to right, " + hex1 + ", " + hex2 + ")";
  document.getElementById("description").innerHTML = "The code of the color is: linear-gradient( 270deg, " + hex1 + ", " + hex2 + " );";
};

此外,如果您使用 div,您也必须定义高度。

使用下面的代码。成功了

document.getElementById('container').style.background = `linear-gradient(to right, ${hex1} , ${hex2} )`;