Java Reference
In-Depth Information
<head>
<title>Chapter 6: Example 2</title>
</head>
<body>
<script type=”text/javaScript”>
switch (window.screen.colorDepth)
{
case 1:
case 4:
document.bgColor = “white”;
break;
case 8:
case 15:
case 16:
document.bgColor = “blue”;
break;
case 24:
case 32:
document.bgColor = “skyblue”;
break;
default:
document.bgColor = “white”;
}
document.write(“Your screen supports “ + window.screen.colorDepth +
“bit color”);
</script>
</body>
</html>
Save the page as
ch6_examp2.htm
. When you load it into your browser, the background color of the
page will be determined by your current screen color depth. Also, a message in the page will tell you
what the color depth currently is.
You can test that the code is working properly by changing the colors supported by your screen. On
Windows XP, you can do this by right-clicking on the desktop and choosing the Properties option. Under
the Settings tab, there is a section called “Color quality” in which you can change the number of colors
supported. By refreshing the browser, you can see what difference this makes to the color of the page.
In Firefox, Safari, and Chrome browsers, it's necessary to shut down and restart the browser to observe
any effect.
As you saw earlier, the
window
object has the
screen
object property. One of the properties of this
object is the
colorDepth
property, which returns a value of
1
,
4
,
8
,
15
,
16
,
24
, or
32
. This represents
the number of bits assigned to each pixel on your screen. (A pixel is just one of the many dots that your
screen is made up of.) To work out how many colors you have, you just calculate the value of
2
to the
power of the
colorDepth
property. For example, a
colorDepth
of
1
means that there are two colors
available, a
colorDepth
of
8
means that there are
256
colors available, and so on. Currently, most
people have a screen color depth of at least
8
, but usually
24
or
32
.
The fi rst task of the script block is to set the color of the background of the page based on the number of
colors the user can actually see. You do this in a big switch statement. The condition that is checked for
in the switch statement is the value of window.screen.colorDepth.
switch (window.screen.colorDepth)