首页 > 解决方案 > 如何使用 javascript 设置 backgroundImage

问题描述

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 + " );";
};

您好,我正在尝试将线性渐变的两种颜色设置为特定元素的背景图像属性中的参数,但我的 setProperty 似乎有问题。除了这行代码,一切都运行良好。 我也试过 style.backgroundImage 没有结果。 我是 js 新手。 提前致谢

标签: javascriptcssbackground-imagegetelementbyidlinear-gradients

解决方案


首先,这里有一个提示:永远不要使用 '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,则还必须定义高度。


推荐阅读