现在我正在尝试开发一个非常简单的按钮来改变整个网页的背景颜色。这是我的代码
var mybutton = document.querySelector('button');
var myBack = document.querySelector("body");
var isRand = false;
var ranNumber1 = Math.floor(Math.random() * 256);
var ranNumber2 = Math.floor(Math.random() * 256);
var ranNumber3 = Math.floor(Math.random() * 256);
var RanRGB = "rgb(" + ranNumber1 + "," + ranNumber2 + "," + ranNumber3 + ")";
mybutton.addEventListener("click", function() {
if (isRand) {
myBack.style.backgroundColor = "white";
isRand = false;
} else {
myBack.style.backgroundColor = RanRGB
isRand = true;
}
});

<!DOCTYPE html>
<html>
<head>
<title>toggle</title>
</head>
<body>
<div>
<button>click here!</button>
</div>
<script type="text/javascript" src="togglescript.js"></script>
</body>
</html>
&#13;
当此网页加载并单击按钮时,背景颜色将从白色变为随机颜色。然后,如果我再次点击它再次变白。这就是我要的。但是,我希望能够再次单击该按钮并将颜色更改为新的随机颜色。目前它只是将背景改回原来生成的颜色。如何重置背景颜色?
答案 0 :(得分:2)
将颜色生成移动到您的功能中。
var mybutton = document.querySelector('button');
var myBack = document.querySelector("body");
var isRand = false;
mybutton.addEventListener("click", function() {
var ranNumber1 = Math.floor(Math.random() * 256);
var ranNumber2 = Math.floor(Math.random() * 256);
var ranNumber3 = Math.floor(Math.random() * 256);
var RanRGB = "rgb(" + ranNumber1 + "," + ranNumber2 + "," + ranNumber3 + ")";
if (isRand) {
myBack.style.backgroundColor = "white";
isRand = false;
} else {
myBack.style.backgroundColor = RanRGB
isRand = true;
}
});