我用JavaScript写了一段代码,如下所示:在这段代码中,onClick按钮想要调用函数fadetext()
,函数fadetext()
本身设置超时。
hex = 255 // Initial color value.
function fadetext()
{
if (hex > 0) { //If color is not black yet
hex -= 11; // increase color darkness
document.getElementById("sample").style.color = "rgb(" + hex + "," + hex + "," + hex + ")";
setTimeout(fadetext, 20);
}
else hex = 255 //reset hex value
}
<div id="sample" style="width:100%">
<h3>John slowly faded into view</h3>
</div>
<button onClick=fadetext()>Fade Text</button>
然而,当我提到答案时,差异显示在以下两行代码中:
setTimeout("fadetext()",20);
另一个是:
<button onClick="fadetext()">Fade Text</button>
有人能帮我解释一下为什么这也有效吗?
setTimeout
引用了超时到期时应该调用的函数,而不是字符串。
尽管setTimeout
可以采用eval
d的字符串,
请不要使用它
,它与eval()
一样具有安全风险。
setTimeout("fadetext()",20);
应为setTimeout(fadetext,20);
并且CCD_ 9属性都是小写的。
<button onClick="fadetext()">Fade Text</button>
应为<button onclick="fadetext()">Fade Text</button>
var hex = 255 // Initial color value.
function fadetext() {
if (hex > 0) { //If color is not black yet
hex -= 11; // increase color darkness
document.getElementById("sample").style.color = "rgb(" + hex + "," + hex + "," + hex + ")";
setTimeout(fadetext, 20);
} else hex = 255 //reset hex value
}
<div id="sample" style="width:100%">
<h3>John slowly faded into view</h3>
</div>
<button onclick="fadetext()">Fade Text</button>