JavaScript 消息框
警告框:alert(“请输入正确的密码!”);
确认框:confirm(“文本”);
提示框:prompt(“文本”,”默认值”);
JavaScript 测试和捕捉
try { //在这里运行代码 }catch(err) { //在这里处理错误 }
typeof运算符
返回一个用来表示表达式的数据类型的字符串。
适合基本类型及function检测,遇到null失效。
Window 对象
Window 对象表示浏览器中打开的窗口。
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;
JavaScript Window Screen
window.screen //对象包含有关用户屏幕的信息。
screen.availWidth //可用的屏幕宽度
screen.availHeight //可用的屏幕高度
JavaScript Window Location
window.location //对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。
location.href //属性返回当前页面的 URL。
location.hostname // 返回 web 主机的域名
location.assign() // 方法加载新的文档。
location.pathname //返回当前页面的路径和文件名
location.port //返回 web 主机的端口 (80 或 443)
location.protocol //返回所使用的 web 协议(http:// 或 https://)
JavaScript Window History
window.history //对象包含浏览器的历史。
history.back() //与在浏览器点击后退按钮相同
history.forward() // 与在浏览器中点击按钮向前相同
JavaScript Window Navigator
window.navigator //对象包含有关访问者浏览器的信息。
navigator.appName //保存浏览器类型
navigator.appVersion // 存有浏览器的版本信息(其他信息中的一项)
JavaScript 动画
使用 JavaScript 通过不同的事件来切换不同的图像。
例子:
onMouseOver 事件的作用是告知浏览器:一旦鼠标悬浮于图像之上,浏览器就会执行某个函数,这个函数会把这副图像替换为另一幅。
onMouseOut 事件的作用是告知浏览器:一旦鼠标离开图像,浏览器就要执行另一个函数,这个函数会重新插入原来的那幅图像。
JavaScript 计时
setTimeout() //未来的某时执行代码
clearTimeout() // 取消setTimeout()
例子:
var t=setTimeout("javascript语句",毫秒);
clearTimeout(t);
tips:计时器设置类似全局设置,可以在不同函数间控制。
JavaScript 表单验证
JavaScript 可用来在数据被送往服务器前对 HTML 表单中的这些输入数据进行验证。
简单例子:
<html>
<head>
<title>用户登录</title>
<script language="javascript" type="text/javascript">
function sub()
{
var user = document.form1.user.value;
var pass = document.form1.pass.value;
if(user=="")
{
alert("用户名不能为空!");
return ;
}else if(pass=="")
{
alert("密码不能为空!");
return;
}else
{
document.form1.submit();
}
}
</script>
</head>
<body>
<form action="authpage.asp" method="post" name="form1">
用户名:<input type="text" name="user" style="width: 80px" />
密码:<input type="text" name="pass" style="width: 80px" />
<input type="button" name="login" value="提交" onClick="sub()" />
</form>
</body>
</html>