一、时间对象
在讲计时器之前,我们先来了解一下时间对象,new Date()时间对象。JavaScript中的时间对象和Java中的时间对象相差不多,都是来获取时间的。
①getTime():返回从 1970 年 1 月 1 日至今的毫秒数
②getMonth():获取月份(月份从0-11)
③getDate():获取天数
④getHours():获取小时
⑤getMinutes():获取分钟数
⑥getSeconds():获取秒数
⑦getMilliseconds():获取毫秒数
⑧getDay():获取星期数,返回0-6,0表示星期日
二、计时器(计时事件)
①setInterval() :间隔指定的毫秒数不停地执行指定的代码:setInterval(function(){逻辑代码},时间间隔);
②clearInterval() :用于停止 setInterval() 方法执行的函数代码
③setTimeout() :返回某个值
④clearTimeout() :用于停止执行setTimeout()方法的函数代码
下面我们通过代码来学习,需求:写一个电子时钟,可以停止时间和开始
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>电子时钟</title>
<script type="text/javascript" src="../../js/电子时钟/time.js" ></script>
</head>
<body>
时间:<input type="text" id="clock1" size="50"/>
<input type="button" onclick="start1()" value="开始" />
<input type="button" value="停止" onclick="clearInterval(i)"/><br />
格式化时间:<input type="text" id="clock2" size="50"/>
<input type="button" onclick="start2()" value="开始" />
<input type="button" value="停止" onclick="clearInterval(j)" />
</body>
</html>
function clock1(){
//获取时间并赋值给clock1
var time=new Date();
document.getElementById("clock1").value = time;
}
//设置每隔一秒更新时间
var i = setInterval("clock1()",100);
function start1(){
i = setInterval("clock1()",100);
}
function clock2(){
////获取时间并赋值给clock2
var time = new Date();
var w = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
document.getElementById("clock2").value = time.getFullYear()+"年"+(time.getMonth()+1)+"月"+time.getDate()+"日"+time.getHours()+"时"+time.getMinutes()+"分"+time.getSeconds()+"秒"+w[time.getDay()];
}
var j = setInterval("clock2()",100);
function start2(){
j = setInterval("clock2()",100);
}
三、JavaScript Cookie
Cookie用于存储web页面的用户信息。是一些数据,存储于电脑上的文本文件。
当 web 服务器向浏览器发送 web 页面时,在连接关闭后,服务端不会记录用户的信息。Cookie 的作用就是用于解决 "如何记录客户端的用户信息":当用户访问 web 页面时,他的名字可以记录在 cookie 中。 在用户下一次访问该页面时,可以在 cookie 中读取用户访问记录。 Cookie 以名/值对形式存储。当浏览器从服务器上请求 web 页面时, 属于该页面的 cookie 会被添加到该请求中。服务端通过这种方式来获取用户的信息。
通过代码来展示:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="../../js/保存信息到cookie/SaveCookie.js" ></script>
</head>
<body>
请输入用户名:<input type="text" id="username" /><br />
请输入密码:<input type="password" id ="password" /><br />
<input type="button" value="保存cookie信息" onclick="savecookie()" />
<input type="button" value="获取cookie信息" onclick="getcookie()" />
</body>
</html>
function savecookie(){
var username = document.getElementById("username").value;
var pwd = document.getElementById("password").value;
document.cookie = "username=" + username;
document.cookie = "password=" + pwd;
}
function getcookie(){
var userinfo = document.cookie.split(";");
for(var i = 0;i < userinfo.length;i++){
var key = userinfo[i].split("=")[0];
var value = userinfo[i].split("=")[1];
alert(key + "--" + value);
}
}