<body>
<H2 align = "center"> adjust the browser window size </H2> <HR>
<form action="#" method="get" name="form1" id="form1">
<! -- Display the actual size of the browser window -->
Actual browser window height: <input type = "text" name = "availheight" size = "4"> <br>
Actual browser window width: <input type = "text" name = "availwidth" size = "4"> <br>
</form>
<script type="text/javascript">
<!--
var winWidth = 0;
var winHeight = 0;
Function finddimensions () // function: obtains the size.
{
// Obtain the window width
if (window.innerWidth)
winWidth = window.innerWidth;
else if ((document.body) && (document.body.clientWidth))
winWidth = document.body.clientWidth;
// Obtain the window height
if (window.innerHeight)
winHeight = window.innerHeight;
else if ((document.body) && (document.body.clientHeight))
winHeight = document.body.clientHeight;
// Detects the body in the document to obtain the window size.
if (document.documentElement && document.documentElement.clientHeight &&
document.documentElement.clientWidth)
{
winHeight = document.documentElement.clientHeight;
winWidth = document.documentElement.clientWidth;
}
// Output the result to two text boxes
document.form1.availHeight.value= winHeight;
document.form1.availWidth.value= winWidth;
}
Finddimensions (); // call a function to obtain a value
window.onresize=findDimensions;
//-->
</script>
</body>
After the program is run, two text boxes are displayed, showing the current width and height of the window, 30.7 respectively. When the browser window size is adjusted, the value in the text box changes accordingly. The values shown in Figure 30.8, figure 30.9, and figure 30.10 are the size of the window at different times.
Figure 30.7 code 30.3.htm display result figure 30.8 display result after widening
Figure 30.9 Display Results After height increase figure 30.10 Display Results After width and height
Source program explanation
(1) The program first creates a form that contains two text boxes to display the current width and height of the window, and the value changes with the size of the window.
(2) In subsequent JavaScript code, two variables winwidth and winheight are defined to save the height and width values of the window.
(3) then, in the finddimensions () function, use window. innerheight and window. innerwidth to get the height and width of the window, and save the two in the preceding two variables.
(4) Check the body in the document to obtain the window size and store it in the preceding two variables.
(5) At the end of the function, access the form element by name and output the result to two text boxes.
(6) at the end of the JavaScript code, complete the operation by calling the finddimensions () function.