脚本化浏览器窗口

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 οnclick="bounce.start()">Start</button> <button οnclick="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 minute setInterval(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 bar function 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 form function 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 it function 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" οnsubmit="go(); return false;"> <input type="button" value="Back" οnclick="back();"> <input type="button" value="Forward" οnclick="forward();"> URL: <input type="text" name="url" size="50"> <input type="button" value="Go" οnclick="go();"> <input type="button" value="Open New Window" οnclick="displayInNewWindow();"> </form>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值