2 回答

TA贡献1804条经验 获得超2个赞
没有返回任何内容,因此修复它的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);
}

TA贡献1804条经验 获得超3个赞
您必须简化您的 GetValue 函数:只需创建 1 个值并返回它。其余的都可以。
让我们在这里试试:
function GetValue() {
var myarray = new Array( "#ff0000", "#ffe100", "#95ff00", "#2c8d94", "#ad6428", "#28ad9d");
return myarray.splice(Math.floor(Math.random() * myarray.length),1)[0];
}
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);
}
document.getElementById('btn').addEventListener('click', function() {
changeBg();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='message'></div>
<input id='myInput'>
<button id='btn'>Click me</button>
添加回答
举报