簡體   English   中英

如何使用javascript設置backgroundImage

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

您好,我正在嘗試將線性漸變的兩種顏色設置為特定元素的背景圖像屬性中的參數,但我的 setProperty 似乎有問題。 除了這行代碼外,一切正常。 我也用 style.backgroundImage 嘗試過,但沒有結果。 我是 js 的新手。 提前致謝

首先,這里有一個提示:永遠不要使用“var”,而要使用“let”。 JS 中沒有setProperty()函數,需要使用element.style["style you want to change"] = "what you want to change it to" 而且,您不應該將變量包裝在 '{}'s 中,否則它們將變成非變量,因此代碼應該是:

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} )`;

暫無
暫無

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

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