我被这个小节拍器项目困住了。它应该在两种背景颜色之间来回闪烁。只要定义了两种颜色,它就可以正常工作(将 JS 第 12 行中的“col”切换为任何颜色,它就可以工作)。不过,我也试图做到这一点,以便我可以在单击时随机化其中一种颜色。我可以告诉(console.log)我的数字随机发生器正在为我的变量“col”生成正确的十六进制颜色值,但我无法让该变量工作。我尝试过不带引号的“col”。
这里是代码笔的链接:http://codepen.io/Fedreg/pen/xVqwjQ/
<head></head>
<body>
<div id="title">
flashnome
</div>
<div id="desc">
the silent metronome
<p>
<button onclick="slower();" id="button1">
slower
</button>
<button onclick="faster();" id="button1">
faster
</button>
</p>
<p>
<button onclick="change();" id="button1">Change Color</button>
</p>
</div>
</body>
@import url(https://fonts.googleapis.com/css?family=Josefin+Sans:400,700);
html, body {
height: 100%;
width:100%;
}
#title {
text-align: center;
color: white;
font-size: 5em;
font-family: 'Josefin Sans', sans-serif;
margin: auto;
text-transform: uppercase;
padding: 2em 0 .2em;
}
#desc {
text-align: center;
color: white;
font-size: 2em;
font-family: 'Josefin Sans', sans-serif;
margin: auto;
text-transform: uppercase;
padding: 0;
}
#button1 {
text-align: center;
font-size: .7em;
font-family: 'Josefin Sans', sans-serif;
margin: 0 auto;
text-transform: uppercase;
padding: 8px;
}
var x = 500;
var flashStep = 1;
var myInterval;
function change() {
var col = '#' + (Math.random().toString(16) + '000000').slice(2, 8);
console.log(col);
}
function flash() {
if (flashStep == 1) {
document.bgColor = "col";
flashStep = 2;
} else {
document.bgColor = "#333";
flashStep = 1;
}
}
function faster() {
window.clearInterval(myInterval);
myInterval = window.setInterval(flash, x -= 25);
}
function slower() {
window.clearInterval(myInterval);
myInterval = window.setInterval(flash, x += 25);
}
myInterval = window.setInterval(flash, x);
function change() {
var col = '#' + (Math.random().toString(16) + '000000').slice(2, 8);
console.log(col);
}
最佳答案
创建一个名为“randomColor”的全局变量并更改它。
var x = 500;
var flashStep = 1;
var myInterval;
var randomColor = "#FFFF00";
function change() {
var col = '#' + (Math.random().toString(16) + '000000').slice(2, 8);
randomColor = col;
console.log(col);
}
function flash() {
if (flashStep == 1) {
document.bgColor = randomColor;
flashStep = 2;
} else {
document.bgColor = "#333";
flashStep = 1;
}
}
function faster() {
window.clearInterval(myInterval);
myInterval = window.setInterval(flash, x -= 25);
}
function slower() {
window.clearInterval(myInterval);
myInterval = window.setInterval(flash, x += 25);
}
myInterval = window.setInterval(flash, x);
关于javascript - javascript 中的变量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36194343/