Document 文件物件是 JavaScript 中 window 與 frames 物件的一個屬性,代表顯示於視窗或框架內的文件,包含了從 <head> 到 </body> 的所有內容。用法為 document(目前視窗)或 <視窗物件>.document(指定視窗)。
document.title // 設定文件標題,等同 HTML 的 <title> document.bgColor // 設定頁面背景色 document.fgColor // 設定前景色(文字顏色) document.linkColor // 未點擊過的連結顏色 document.alinkColor // 作用中連結的顏色 document.vlinkColor // 已點擊過的連結顏色 document.URL // 設定 URL,可在同一視窗開啟另一網頁 document.fileCreatedDate // 檔案建立日期(唯讀) document.fileModifiedDate // 檔案修改日期(唯讀) document.fileSize // 檔案大小(唯讀) document.cookie // 設定與讀出 cookie document.charset // 設定字元集,簡體中文為 gb2312
此外還有幾個實用屬性:lastModified(最後修改日期,Date 物件)、referrer(若目前文件是透過點擊連結開啟,則回傳原來的 URL)、title、fgColor、bgColor、linkColor、alinkColor、vlinkColor 等。
open():打開文件以便寫入資料,通常會自動呼叫。write() 與 writeln():向文件寫入資料,內容會被當成標準 HTML 處理。writeln 會在寫入後加一個換行。clear():清空目前文件。close():關閉文件、停止寫入。若用過 write[ln]() 或 clear(),就一定要用 close() 確保變更顯示出來。有了這些知識,就能做出很多網站都有的更新通知視窗:
<script language="JavaScript">
var whatsNew = open('', '_blank', 'top=50,left=50,width=200,height=300,'
+ 'menubar=no,toolbar=no,directories=no,location=no,'
+ 'status=no,resizable=no,scrollbars=yes');
whatsNew.document.write('<center><b>更新通知</b></center>');
whatsNew.document.write('<p>最後更新日期:00.08.01');
whatsNew.document.write('<p>00.08.01:增加了「我的最愛」欄目。');
whatsNew.document.write('<p align="right">'
+ '<a href="javascript:self.close()">關閉視窗</a>');
whatsNew.document.close();
</script>
當然,也可以先寫好一個 HTML 檔,再在 open() 方法中直接載入該檔案。