JavaWeb:(练习)六、JavaScript-计数、计时练习
JavaWeb:(练习)六、JavaScript-计数、计时练习
一、计数器练习
1、练习目标
制作一个计数器,点击开始从1开始计数,点击停止,停止计数,点击复位归0并结束计数(可以参考手机上的定时器)
2、HTML代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>计数器</title>
<link href="Demo.css" rel="stylesheet" type="text/css" />
<script src="Demo.js" type="text/javascript"></script>
</head>
<body>
<div class="box">
<input id="screen" type="text" value="1" readonly="readonly" /> <br />
<input id="start_id" type="button" value="开始" onclick="start()" />
<input id="stop_id" type="button" value="停止" onclick="stop()" />
<input id="reset_id" type="button" value="复位" onclick="reset()" />
</div>
</body>
</html>
3、CSS代码
*{
margin: 0;
padding: 0;
}
.box{
background-color: skyblue;
width: 300px;
height: 100px;
text-align: center;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
}
#screen{
width: 100px;
height: 30px;
background-color: white;
text-align: center;
}
input{
background-color: #aaffff;
margin-top: 10px;
width: 50px;
height: 30px;
}
4、js代码
var t;
function add(){
var screenObj = document.getElementById("screen");
var number = parseInt(screenObj.value)+1;
document.getElementById("screen").value = ""+number;
}
function start() {
t = setInterval("add()", 1000);
}
function stop() {
clearInterval(t);
console.log("执行了一次");
}
function reset() {
document.getElementById("screen").value = "1";
}
5、网页结果
二、电子表练习
1、练习目标
制作电子表,在页面显示一个年月日 时分秒的时间,使其每秒更新一次.
2、HTML代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>时间电子表</title>
<link href="Demo.css" rel="stylesheet" type="text/css" />
<script src="Demo.js" type="text/javascript"></script>
</head>
<body>
<div class="box">
<div class="clock">
<span class="time_id"></span>
<span class="time_id"></span>
<span class="time_id"></span>
<span class="time_id"></span>
<span class="time_id"></span>
<span class="time_id"></span>
</div>
</div>
</body>
</html>
3、CSS代码
*{
margin: 0;
padding: 0;
}
.box{
background-color: lightgoldenrodyellow;
border: 2px black solid;
border-radius: 30px;
width: 500px;
height: 100px;
margin: auto;
margin-top: 100px;
text-align: center;
}
.clock{
width: 500px;
margin-top: 30px;
float: left;
}
span{
color: red;
font-size: 40px;
font-family: 楷体;
padding-top: 200px;
}
4、js代码
var t = setInterval("setTime()", 100);
function setTime() {
var timeObjs = document.getElementsByClassName("time_id");
var date = new Date();
timeObjs[0].innerHTML = date.getFullYear() + "年";
timeObjs[1].innerHTML = date.getMonth() + "月";
timeObjs[2].innerHTML = date.getDay() + "日";
if(date.getHours()<10){
timeObjs[5].innerHTML = "0" + date.getHours();
} else {
timeObjs[3].innerHTML = date.getHours() + ":";
}
if(date.getMinutes()<10){
timeObjs[5].innerHTML = "0" + date.getMinutes();
} else {
timeObjs[4].innerHTML = date.getMinutes() + ":";
}
if(date.getSeconds()<10){
timeObjs[5].innerHTML = "0" + date.getSeconds();
} else {
timeObjs[5].innerHTML = date.getSeconds();
}
}