Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Javascript将api中的rgb数据作为背景应用于html元素_Javascript - Fatal编程技术网

使用Javascript将api中的rgb数据作为背景应用于html元素

使用Javascript将api中的rgb数据作为背景应用于html元素,javascript,Javascript,我在使用javascript将api生成的数据设置为背景样式时遇到问题。我尝试添加一个静态值,如element.style.backgroundColor=blue,它可以正常工作,但我没有幸使用element.style.backgroundColor=color 包含数据的Javascript: scheme.forEach(colour => { console.log(colour) // successful data collected const column = d

我在使用javascript将api生成的数据设置为背景样式时遇到问题。我尝试添加一个静态值,如
element.style.backgroundColor=blue
,它可以正常工作,但我没有幸使用
element.style.backgroundColor=color

包含数据的Javascript:

scheme.forEach(colour => {
  console.log(colour) // successful data collected
  const column = document.createElement('div')
  column.setAttribute('class', 'column')

  app.appendChild(column)
  column.style.backgroundColor = colour
})
控制台日志中的示例数据:


这是因为在
color
中得到的值是一个数组,而不是一个色码。您应该将数组解析为颜色代码(即RGB格式)


您需要传递
rgb
以及值

尝试下面的解决方案

scheme.forEach(colour => {
  console.log(colour) // successful data collected
  const column = document.createElement('div')
  column.setAttribute('class', 'column')

  app.appendChild(column)
  column.style.backgroundColor = `rgb(${colour})`
})

不应将数组作为颜色传递,而应使用该数组中的元素创建一个
rgb()
字符串。您可以为此创建一个函数

constdiv=document.querySelector('div');
const rgb=color=>`rgb(${color.join(',')})`
div.style.backgroundColor=rgb([50,200,50])

Div
您可以尝试以下方法:

var方案=[[122122122],[222122122],[122322122]]
scheme.forEach(颜色=>{
//console.log(彩色)//成功收集数据
const column=document.createElement('div');
column.textContent='test';
setAttribute('class','column');
document.body.appendChild(列)
column.style.backgroundColor='rgb('+color.join(',')+');
})
scheme.forEach(colour => {
  console.log(colour) // successful data collected
  const column = document.createElement('div')
  column.setAttribute('class', 'column')

  app.appendChild(column)
  column.style.backgroundColor = `rgb(${colour})`
})