1、計時器
任何編程環境的一個重要的功能就是規劃代碼在未來的某個時刻執行。核心JavaScript語言並沒有提供這樣的功能,但是用戶端JavaScript確實以全域函數setTimeout()、clearTimeout()、setInterval()、clearInterval()的形式提供了這一功能。
Window對象的setTimeout()方法用來安排一個函數在指定的毫秒數過去之後運行。setTimeout()返回一個不確定的值,這個值可以傳遞給clearTimeout()來取消規劃的函數的執行。
setInterval()和setTimeout()一樣,只不過指定的函數在一個指定的毫秒數的間隔裡重複地調用。和setTimeout()一樣,setInterval()也返回一個不確定的值,這個值可以傳遞給clearInterval()用來取消規劃的函數的任何未來的調用。
2、瀏覽器Location和History
這兩個對象提供了當前顯示的文檔的URL的訪問,並且允許載入新的文檔或者讓瀏覽器後退(或前進)到一個之前瀏覽過的文檔。
2.1、解析URL
視窗的location屬性引用的是Location對象,它代表該視窗(或幀)中當前顯示的文檔的URL。Location對象的href屬性是一個字串,它包含URL的完整文本。Location對象toString()方法返回href屬性的值。因此可以使用location代替location.href。
2.2、載入新的文檔
儘管一個視窗的location屬性引用了一個Location對象,還是可以給這個屬性賦值一個字串。當這麼做的時候,瀏覽器把這個字串解釋為一個URL,並且試圖用這個URL載入和顯示文檔。
Location對象有兩種實現讓瀏覽器載入和顯示一個新的頁面目的的方法。
方法reload()會從Web伺服器上再次裝入當前顯示的頁面。方法replace()會裝載並顯示指定的URL。當為給定的URL調用這個方法和把一個URL賦給視窗的location屬性不同。當調用replace()時,指定的URL就會替換瀏覽器曆史列表中的當前URL,而不是在曆史列表中建立一個新條目。因此,如果使用方法replace()使一個新文檔覆蓋當前文檔,Back按鈕就不能使使用者返回最初文檔,而通過將一個URL賦給視窗的location屬性來裝載新文檔就能做到這一點。
注意:不要混淆Window對象的location屬性和Document對象的location屬性。前者引用一個Location對象,而後者只是一個唯讀字串,並不具有Location對象的任何特性。document.location與document.URL是同義的,後者是該屬性的候選名稱。在大多數情況下,document.location和location.href是相同的。當時,當存在伺服器重新導向時,document.location包含的是已經裝載的URL,而location.href包含的則是原始請求的文檔的URL。
2.3、History對象
Window對象的history屬性引用的是該視窗的History對象。History對象最初是用來把視窗的瀏覽曆史構造成最近訪問過的URL的數組。
儘管History對象的數組元素不能被訪問,但它支援三種方法。方法back()和forward()可以在視窗(或幀)的瀏覽曆史中前後移動,用前面瀏覽過的文檔替換當前顯示的文檔,這與使用者點擊瀏覽器的Back和Forward按鈕的作用相同。第三個方法go()有一個整數參數,可以在曆史列表中向前(正參數)或向後(負參數)跳過多個頁。
3、擷取視窗、螢幕和瀏覽器資訊
指令碼有時候需要擷取和它們在其中啟動並執行視窗、案頭或瀏覽器相關的資訊。
3.1、視窗的集合大小
下面的詳細例子,定義了一個Geometry對象,該對象帶有可移植的查詢視口大小、移動條位置和螢幕位置的方法。
/** * Geometry.js: portable functions for querying window and document geometry * * This module defines functions for querying window and document geometry. * * getWindowX/Y(): return the position of the window on the screen * getViewportWidth/Height(): return the size of the browser viewport area * getDocumentWidth/Height(): return the size of the document. * getHorizontalScroll(): return the position of the horizontal scrollbar * getVerticalScroll(): return the position of the vertical scrollbar * * Note that there is no portable way to query the overall size of the * browser window, so there are no getWindowWidth/Height() functions. * * IMPORTANT: This module must be included in the <body> of a document * instead of the <head> of the document. */var Geometry = {};if (window.screenLeft) { // IE and others Geometry.getWindowX = function() { return window.screenLeft; }; Geometry.getWindowY = function() { return window.screenTop; };}else if (window.screenX) { // Firefox and others Geometry.getWindowX = function() { return window.screenX; }; Geometry.getWindowY = function() { return window.screenY; };}if (window.innerWidth) { // All browsers but IE Geometry.getViewportWidth = function() { return window.innerWidth; }; Geometry.getViewportHeight = function() { return window.innerHeight; }; Geometry.getHorizontalScroll = function() { return window.pageXOffset; }; Geometry.getVerticalScroll = function() { return window.pageYOffset; };}else if (document.documentElement && document.documentElement.clientWidth) { // These functions are for IE6 when there is a DOCTYPE Geometry.getViewportWidth = function() { return document.documentElement.clientWidth; }; Geometry.getViewportHeight = function() { return document.documentElement.clientHeight; }; Geometry.getHorizontalScroll = function() { return document.documentElement.scrollLeft; }; Geometry.getVerticalScroll = function() { return document.documentElement.scrollTop; };}else if (document.body.clientWidth) { // These are for IE4, IE5, and IE6 without a DOCTYPE Geometry.getViewportWidth = function() { return document.body.clientWidth; }; Geometry.getViewportHeight = function() { return document.body.clientHeight; }; Geometry.getHorizontalScroll = function() { return document.body.scrollLeft; }; Geometry.getVerticalScroll = function() { return document.body.scrollTop; };}// These functions return the size of the document. They are not window // related, but they are useful to have here anyway.if (document.documentElement && document.documentElemnet.scrollWidth) { Geometry.getDocumentWidth = function() { return document.documentElement.scrollWidth; }; Geometry.getDocumentHeight = function() { return document.documentElement.scrollHeight; };}else if (document.body.scrollWidth) { Geometry.getDocumentWidth = function() { return document.body.scrollWidth; }; Geometry.getDocumentHeight = function() { return document.body.scrollHeight; };}
3.2、Screen對象
Window對象的screen屬性引用Screen對象。這個Screen對象提供有關使用者顯示器的大小和可用的顏色數量的資訊。屬性width和height指定的是以像素為單位的顯示器大小。屬性availWidth和availHeight指定的是實際可用的顯示大小,它們排除了像案頭工作列這樣的特性所佔有的空間。
3.3、Navigator對象
Window對象的navigator屬性引用的是包含Web瀏覽器總體資訊(如版本和它可以顯示的資料格式列表)的Navigator對象。
Navigator對象有五個屬性用於提供正在啟動並執行瀏覽器的版本資訊:
appName:瀏覽器的簡單名稱。
appVersion:瀏覽器的版本號碼和(或)其他版本資訊。
userAgent:瀏覽器在它的USER-AGENT HTTP頭部中發送的字串。這個屬性通常包含appName和appVersion中的所有資訊,並且,常常也可能包含其他的細節。
appCodeName:瀏覽器的代碼號。
platform:運行瀏覽器的硬體平台。
4、開啟和操作視窗
4.1、開啟視窗
Window.open()方法可以開啟一個新的瀏覽器視窗,返回的是代表新開啟的視窗的Window對象。open()第一個參數是要在新視窗中顯示的文檔的URL,第二個參數是新開啟的視窗的名字,第三個參數是特性列表,第四個參數只在第二個參數命名的是一個存在的視窗時才有用。
4.2、關閉視窗
就像方法open()開啟一個新視窗一樣,方法close()將關閉一個視窗。
4.3、視窗的幾何大小
方法moveTo()可以將視窗的左上方移動到指定的座標。同樣,方法moveBy()可以將視窗上移、下移或者左移、右移指定數量的像素。方法resizeTo()和resizeBy()可以按照相對數量和絕對數量調整視窗的大小。
4.4、鍵盤焦點和可見度
方法focus()會請求系統將鍵盤焦點賦予視窗,blur()則會放棄鍵盤焦點。
4.5、滾動
Window對象還具有一些在視窗或幀中滾動文檔的方法。scrollBy()會將視窗中顯示的文檔向左、向右或者向上、向下滾動指定數量的像素。scrollTo()會將文檔滾動到一個絕對位置。
在現代瀏覽器中,文檔的HTML元素有offsetLeft和offsetTop屬性來指定元素的X座標和Y座標。一旦已經確定了元素的位置,可以使用scrollTo()來滾動一個視窗,以使任何指定元素位於視窗的左上方位置。
滾動的另一種方法是調用文件項目(如表單欄位或按鈕)的focus()方法,它可以接收鍵盤焦點。作為把焦點傳遞給元素的過程的一部分,滾動文檔以使元素變得可見。
4.6、Window方法樣本
<script>var bounce = { x:0, y:0, w:200, h:200, // Window position and size dx:5, dy:5, // Window velocity interval: 100, // Milliseconds between updates win: null, // The window we will create timer: null, // Return value of setInterval() // Start the animation start: function() { // Start with the window in the center of the screen bounce.x = (screen.width - bounce.w)/2; bounce.y = (screen.height - bounce.h)/2; // Create the window that we're going to move around // The javascript: URL is simply a way to display a short document // The final argument specifies the window size bounce.win = window.open('javascript:"<h1>BOUNCE!</h1>"', "", "left=" + bounce.x + ",top=" + bounce.y + ",width=" + bounce.w + ",height=" +bounce.h+ ",status=yes"); // Use setInterval() to call the nextFrame() method every interval // milliseconds. Store the return value so that we can stop the // animation by passing it to clearInterval(). bounce.timer = setInterval(bounce.nextFrame, bounce.interval); }, // Stop the animation stop: function() { clearInterval(bounce.timer); // Cancel timer if (!bounce.win.closed) bounce.win.close(); // Close window }, // Display the next frame of the animation. Invoked by setInterval() nextFrame: function() { // If the user closed the window, stop the animation if (bounce.win.closed) { clearInterval(bounce.timer); return; } // Bounce if we have reached the right or left edge if ((bounce.x+bounce.dx > (screen.availWidth - bounce.w)) || (bounce.x+bounce.dx < 0)) bounce.dx = -bounce.dx; // Bounce if we have reached the bottom or top edge if ((bounce.y+bounce.dy > (screen.availHeight - bounce.h)) || (bounce.y+bounce.dy < 0)) bounce.dy = -bounce.dy; // Update the current position of the window bounce.x += bounce.dx; bounce.y += bounce.dy; // Finally, move the window to the new position bounce.win.moveTo(bounce.x,bounce.y); // Display current position in window status line bounce.win.defaultStatus = "(" + bounce.x + "," + bounce.y + ")"; }}</script><button onclick="bounce.start()">Start</button><button onclick="bounce.stop()">Stop</button>
5、簡單的對話方塊
使用alert()、confirm()和prompt()。
6、指令碼化狀態列
一個優雅的狀態列動畫
<script>var WastedTime = { start: new Date(), // Remember the time we started displayElapsedTime: function() { var now = new Date(); // What time is it now // compute elapsed minutes var elapsed = Math.round((now - WastedTime.start)/60000); // And try to display this in the status bar window.defaultStatus = "You have wasted " + elapsed + " minutes."; }}// Update the status line every minutesetInterval(WastedTime.displayElapsedTime, 60000);</script>
7、錯誤處理
Window對象的onerror屬性比較特殊。如果給這個屬性賦一個函數,那麼只要這個視窗中發生了JavaScript錯誤,該函數就會被調用,即它成了視窗的錯誤處理控制代碼。
8、多視窗和多幀
8.1、幀之間的關係
8.2、視窗和幀的名字
8.3、互動視窗中的JavaScript
9、樣本:幀中的一個導覽列
<!-- This file implements a navigation bar, designed to go in a frame. Include it in a frameset like the following: <frameset rows="*,75"> <frame src="about:blank" name="main"> <frame src="navigation.html"> </frameset> The code in this file will control the contents of the frame named "main"--><script>// The function is invoked by the Back button in our navigation barfunction back() { // First, clear the URL entry field in our form document.navbar.url.value = ""; // Then use the History object of the main frame to go back // Unless the same-origin policy thwarts us try { parent.main.history.back(); } catch(e) { alert("Same-origin policy blocks History.back(): " + e.message); } // Display the URL of the document we just went back to, if we can. // We have to defer this call to updateURL() to allow it to work. setTimeout(updateURL, 1000);}// This function is invoked by the Forward button in the navigation bar.function forward() { document.navbar.url.value = ""; try { parent.main.history.forward(); } catch(e) { alert("Same-origin policy blocks History.forward(): "+e.message);} setTimeout(updateURL, 1000);}// This private function is used by back() and forward() to update the URL// text field in the form. Usually the same-origin policy prevents us from// querying the location property of the main frame, however.function updateURL() { try { document.navbar.url.value = parent.main.location.href; } catch(e) { document.navbar.url.value = "<Same-origin policy prevents URL access>"; }}// Utility function: if the url does not begin with "http://", add it.function fixup(url) { if (url.substring(0,7) != "http://") url = "http://" + url; return url;}// This function is invoked by the Go button in the navigation bar and also// when the user submits the formfunction go() { // And load the specified URL into the main frame. parent.main.location = fixup(document.navbar.url.value);}// Open a new window and display the URL specified by the user in itfunction displayInNewWindow() { // We're opening a regular, unnamed, full-featured window, so we just // need to specify the URL argument. Once this window is opened, our // navigation bar will not have any control over it. window.open(fixup(document.navbar.url.value));}</script><!-- Here's the form, with event handlers that invoke the functions above --><form name="navbar" onsubmit="go(); return false;"> <input type="button" value="Back" onclick="back();"> <input type="button" value="Forward" onclick="forward();"> URL: <input type="text" name="url" size="50"> <input type="button" value="Go" onclick="go();"> <input type="button" value="Open New Window" onclick="displayInNewWindow();"></form>