javascript - 识别元素中的随机背景梯度函数问题
问题描述
我开发了一个程序,我的第一个函数 (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);
}
谢谢
解决方案
没有返回任何东西,因此修复它的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);
}
推荐阅读
- java - 将python字典转换为Java hashmap,其中值类型是数据结构和lambda函数的混合
- algorithm - 如果 f(n) 是 Θ(h(n)) 并且 g(n) = O(h(n)) 那么 f(n) + g(n) 是 Θ(h(n))。对或错
- python - 如何一直使用 selenium 运行 python 脚本,但不在我的 PC 上
- animation - 如何在 gl-matrix 中使用 fromRotationTranslationScaleOrigin 插入多维数据集?
- javascript - 控制器为每个页面请求收到 2 个请求
- python - 为什么我的代码没有返回斜边的值?
- python - 如何显示两个圆圈而不会因双重刷新而闪烁
- rest - 从 Firebase 托管到 REST api 到其他子域的 CORS
- php - 如何更新和删除(取消链接)多个 json 格式的旧图像
- angular - 如何通过角度代码操作离子组件的样式