HTML/DOM: color/bgColor;do 16 个 HTML 颜色以外的值给出(不可)预测的结果



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

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

<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...!

为什么会这样?

您遇到此问题是因为浏览器将尝试解析您设置 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>");
    }
}());

或者继续问问题,直到给出有效的答案。(相当邪恶的海事组织)

(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 使用了这种解释,其他浏览器也遵循这种解释,以免破坏向后兼容性。

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

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

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

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

最新更新