您遇到此问题是因为浏览器将尝试解析您将 bgColor 设置为...
现在你的 Javascript 相当有问题,我想不出你想要这样做的原因,但你的代码应该看起来更像这样。
(function () {
// Prompts the user to give an answer, this prevents further code execution
var sAnswer = window.prompt("Please enter your favourite color : choose from the following Yellow, Green, Red, Blue, Pink, Orange, Black, Gray");
// Takes care of all falsy valuyes, 0, null, undefined, false
// Ideally some more validation on the input should be done
if(sAnswer) {
document.body.style.backgroundColor = sAnswer;
document.write ("<h1>Welcome " + sAnswer + ":-)!!</h1><hr><p>We are very happy to demonstrate the usage of <i> document. write</i>. Do remember to view the source!</p>");
} else {
document.write ("<p>You did not fill in a valid answer! Refresh.</p>");
}
}());
或者继续问这个问题,直到给出一个有效的答案..(相当邪恶的imo)
(function () {
var sAnswer;
do {
sAnswer = window.prompt("Please enter your favourite color : choose from the following Yellow, Green, Red, Blue, Pink, Orange, Black, Gray")
} while ( !sAnswer );
document.body.style.backgroundColor = sAnswer;
document.write ("<h1>Welcome " + sAnswer + ":-)!!</h1><hr><p>We are very happy to demonstrate the usage of <i> document. write</i>. Do remember to view the source!</p>");
}());
代码未经测试但相当有信心它应该可以工作:p
编辑,它是如何变成绿色的?
简而言之,undefined
被类型转换为可用于设置bgColor
属性的字符串,该属性又被解析并解释为颜色,从而使无效的十六进制字符计入0
. 阅读此内容以获得更深入的解释。
Internet Explorer 使用了这种解释,其他浏览器也使用了这种解释,以免破坏向后兼容性。