首页 > 解决方案 > 识别元素中的随机背景梯度函数问题

问题描述

我开发了一个程序,我的第一个函数 (GetValue()) 从我创建的颜色数组中选择两种颜色。这些颜色存储在变量中 - randomColor1 和 randomColor2

接下来,我创建了一个函数来制作我的背景渐变。为此,我调用元素(randomColor1 和 randomColor2)。但它不起作用并且显示错误为(randomColor1 和 randomColor2)未定义,并且我的背景颜色没有改变。

最后,我合并了上述两个函数。

请帮我修复我的代码。我不明白我犯了什么错误。我是菜鸟。

这是我的代码

function GetValue() {
  var myarray = new Array( "#ff0000", "#ffe100", "#95ff00", "#2c8d94", "#ad6428", "#28ad9d");
  var randomColor1 = myarray.splice(
    Math.floor(Math.random() * myarray.length),1)[0];
  var randomColor2 = myarray.splice(
    Math.floor(Math.random() * myarray.length),1)[0];

  document.getElementById("message").innerHTML = randomColor1 + randomColor2;
}


var styles = ["to right", "to bottom right", "-90deg"];


function applyChanges(randomColor1, randomColor2) {
  var randomColor1 = GetValue();
  var randomColor2 = GetValue();
  var bg = "";
  var style = Math.floor(Math.random() * styles.length);
  bg = "linear-gradient(" + styles[style] + "," + randomColor1 + "," + randomColor2 + ")";
  $("body").css("background", bg);
  $("#myInput").text(bg);
}

function changeBg() {
  var randomColor1 = GetValue();
  var randomColor2 = GetValue();
  applyChanges(randomColor1, randomColor2);
}

谢谢

标签: javascripthtmljquerycss

解决方案


没有返回任何东西,因此修复它的GetValue()一种方法是返回两种颜色,然后分配它们,如下所示:

function GetValue() {
    var myarray = new Array("#ff0000", "#ffe100", "#95ff00", "#2c8d94", "#ad6428", "#28ad9d");
    var randomColor1 = myarray.splice(
        Math.floor(Math.random() * myarray.length), 1)[0];
    var randomColor2 = myarray.splice(
        Math.floor(Math.random() * myarray.length), 1)[0];

    /* Return like this*/
    return [randomColor1, randomColor2];
}

并且 changeBG() 更改为
function changeBg() {
    /* Get colors like this since they are returned like this*/
    var [randomColor1, randomColor2] = GetValue();
    /* Log it to see what colors they are*/
    console.log(randomColor1, randomColor2);
    /* Call the apply method*/
    applyChanges(randomColor1, randomColor2);
}

推荐阅读