一個簡單的JavaScript例子
咱們會使用一個簡單的腳原本結束本章。它首先會測量訪問者的屏幕寬度,而後來應用一種合適的樣式(經過在頁面中添加一個額外的LINK元素)。咱們會使用Screen對象,它是用戶屏幕的一種表示。這個對象有一個availWidth 屬性,咱們能夠獲得它,由它來決定該加載那種樣式。
下面是這段代碼:
<!DOCTYPE HTML PUBLIC "-//W
3C
//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>CSS Resolution Demo</title>
<!-- Basic style with all settings -->
<link rel="StyleSheet" href="basic.css" type="text/css" />
<!--
Extra style (applied via JavaScript) to override default settings
according to the screen resolution
-->
<script type="text/javascript">
// Define a variable called cssName and a message
// called resolutionInfo
var cssName;
var resolutionInfo;
// If the width of the screen is less than 650 pixels
if( screen.availWidth < 650 ) {
// define the style Variable as the low-resolution style
cssName = 'lowres.css';
resolutionInfo = 'low resolution';
// Or if the width of the screen is less than 1000 pixels
} else {
if( screen.availWidth > 1000 ) {
// define the style Variable as the high-resolution style
cssName = 'highres.css';
resolutionInfo = 'high resolution';
// Otherwise
} else {
// define the style Variable as the mid-resolution style
cssName = 'lowres.css';
resolutionInfo = 'medium resolution';
}
}
document.write( '<link rel="StyleSheet" href="' +
cssName + '" type="text/css" />' );
</script>
</head>
<body>
<script type="text/javascript">
document.write( '<p>Applied Style:' +
resolutionInfo + '</p>' );
</script>
</body>
</html>
儘管咱們會在下章中看到if語句和循環的詳細講解,但你已經可以大概明白它是如何工做的。第一行的if語句來判斷screen.availWidth 是否小於650:
if ( screen.availWidth < 650 )
若是用戶的屏幕是640*480,那麼它的寬度小於650, 因此大括號裏的代碼會被執行,low-resolution和消息會獲得定義。
if ( screen.availWidth < 650 ) {
// define the style Variable as the low-resolution style
cssName = ‘lowres.css';
resolutionInfo = 'low resolution';
}
代碼使用else語句繼續檢查屏幕的大小。最後的else語句只有在其餘的判斷語句都不執行的時候纔會發生,因此咱們假定屏幕的大小是800*600,對應的定義一個medium樣式和消息。
else {
// define the style Variable as the mid-resolution style
cssName = 'lowres.css';
resolutionInfo = 'medium resolution';
}
這樣也有多是徒勞的,由於咱們在這裏測量用戶的屏幕大小,用戶可能擁有一個800*600的屏幕,可是那不意味着他們的瀏覽器窗口是最大化的。咱們可能應用一種並非很合適的樣式。
咱們使用了另外一個對象:document, 用它來往網頁(HTML文檔)中寫入數據。Document對象的write()方法容許咱們在頁面中插入HTML。注意document.write() 實際上並無改變HTML源文件的內容,只是改變了用戶在他本身電腦上看到的網頁。
n
註解:
實際上,在你看完本書的前幾章後,你就會發現document.write() 很是有用。它很是適合於來展現腳本是如何工做的小例子、與用戶進行交互、甚至對一個你不太肯定的程序段進行調試,以明白它沒有按你預期那樣運行的緣由。它還在全部支持JavaScript的瀏覽器上均可以運行。許多主流的瀏覽器提供了更好的工具和方法來進行調試,咱們會在第三章中會作更多介紹。
咱們使用document.write()來在文件頭中寫一個使用了咱們已定義好的樣式的link元素:
document.write( '<link rel="StyleSheet" href="' +
cssName + '" type="text/css" />' );
並在文檔的主體部分,咱們會寫出信息來講明那種樣式被應用了:
<script type="text/javascript">
document.write( '<p>Applied Style: '+ resolutionInfo + '</p>' );
</script>
稍後,咱們會接觸更復雜的例子,它使用JavaScript來測試用戶代理和用戶界面的類型。如今,我但願這個簡單例子能夠給你一個大體的瞭解,你可使用JavaScript在你的網頁中加入有彈性的元素。