0

在浏览器中运行此代码,如果未输入颜色,则呈现“绿色”(未定义)。

随机/垃圾值导致黑色背景...
...不选择或透明给出白色(空)

<HTML>
<HEAD>
<TITLE>Document Object Demo</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=Javascript>
var sAnswer = window.prompt("Please enter your favourite color : choose from the following Yellow, Green, Red, Blue, Pink, Orange, Black, Gray")
document.bgColor = sAnswer
document. write ("<H1>Welcome " + sAnswer + ":-)!!</H1><HR>We are very happy to demonstrate the usage of <I> document. write</I>. Do remember to view the source!<P>")
</SCRIPT>
</BODY>
</HTML>

我用IE9...!

为什么会这样?

4

2 回答 2

2

您遇到此问题是因为浏览器将尝试解析您将 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 使用了这种解释,其他浏览器也使用了这种解释,以免破坏向后兼容性。

于 2012-05-28T08:51:24.093 回答
1

没有诸如默认颜色之类的东西。在不同的浏览器中有不同的默认 css 样式(请参阅浏览器的默认 CSS 样式表)。

对于您的代码,您很可能应该检查用户提供的答案 set 是否有意义bgColor

此外,此属性已被弃用:https ://developer.mozilla.org/en/DOM/document.bgColor 。

您可能应该通过以下方式设置背景:document.body.style.backgroundColor.

于 2012-05-28T08:38:50.220 回答