1.JavaScript Window
1.Window 尺寸
有三种方法能够确定浏览器窗口的尺寸(浏览器的视口,不包括工具栏和滚动条)。
对于Internet Explorer、Chrome、Firefox、Opera 以及 Safari:
- window.innerHeight - 浏览器窗口的内部高度
- window.innerWidth - 浏览器窗口的内部宽度
对于 Internet Explorer 8、7、6、5:
- document.documentElement.clientHeight
- document.documentElement.clientWidth
或者
- document.body.clientHeight
- document.body.clientWidth
实用的 JavaScript 方案(涵盖所有浏览器):
实例
var w=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var h=window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
其他 Window 方法
一些其他方法:
- window.open() - 打开新窗口
- window.close() - 关闭当前窗口
- window.moveTo() - 移动当前窗口
- window.resizeTo() - 调整当前窗口的尺寸
2.Window Screen
window.screen 对象在编写时可以不使用 window 这个前缀。
一些属性:
- screen.availWidth - 可用的屏幕宽度
- screen.availHeight - 可用的屏幕高度
3.Window Location
window.location 对象在编写时可不使用 window 这个前缀。
一些例子:
- location.hostname 返回 web 主机的域名
- location.pathname 返回当前页面的路径和文件名
- location.port 返回 web 主机的端口 (80 或 443)
- location.protocol 返回所使用的 web 协议(http:// 或 https://)
4.Window Location Assign
location.assign() 方法加载新的文档。
5.Window History
window.history 对象在编写时可不使用 window 这个前缀。
为了保护用户隐私,对 JavaScript 访问该对象的方法做出了限制。
一些方法:
- history.back() - 与在浏览器点击后退按钮相同
- history.forward() - 与在浏览器中点击按钮向前相同
6.消息框
alert("文本")
confirm("文本")
prompt("文本","默认值")
7.JavaScript 计时事件
通过使用 JavaScript,我们有能力作到在一个设定的时间间隔之后来执行代码,而不是在函数被调用后立即执行。我们称之为计时事件。
在 JavaScritp 中使用计时事件是很容易的,两个关键方法是:
-
setTimeout()
- 未来的某时执行代码 clearTimeout()
- 取消setTimeout()
<html> <head> <script type="text/javascript"> var c=0 var t function timedCount() { document.getElementById('txt').value=c c=c+1t=setTimeout("timedCount()",1000)
} function stopCount() {clearTimeout(t)
} </script> </head> <body> <form> <input type="button" value="Start count!" onClick="timedCount()"> <input type="text" id="txt"> <input type="button" value="Stop count!" onClick="stopCount()"> </form> </body> </html>
8.JavaScript Cookie
<html> <head> <script type="text/javascript"> function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "=") if (c_start!=-1) { c_start=c_start + c_name.length+1 c_end=document.cookie.indexOf(";",c_start) if (c_end==-1) c_end=document.cookie.length return unescape(document.cookie.substring(c_start,c_end)) } } return "" } function setCookie(c_name,value,expiredays) { var exdate=new Date() exdate.setDate(exdate.getDate()+expiredays) document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) } function checkCookie() { username=getCookie('username') if (username!=null && username!="") {alert('Welcome again '+username+'!')} else { username=prompt('Please enter your name:',"") if (username!=null && username!="") { setCookie('username',username,365) } } } </script> </head> <body onLoad="checkCookie()"> </body> </html>