CSS结合JavaScript编写的一段在网页上动态显示时间的代码

时间:2024-03-10 14:58:07

使用CSS结合JavaScript可以很方便地实现在网页上动态显示时间的功能,主要应用了CSS的input方法,JavaScript的Date对象中的设置时间间隔setInterval()方法.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>guoming</title>
</head>
<body>
<h1 style="color:red;font-size:30px">Date and Time Author:Guoming Liu</h1>
<input type="text" id="text_box">
<input type="button" value="begin" onclick="begin_click()" style="width:80px">
<input type="button" value="end" onclick="end_click()" style="width:80px">
<script>
function gettime(){
var d=new Date();
var year=d.getFullYear();
var month=d.getMonth()+1;
var day=d.getDate();
var hour=d.getHours();
var minute=d.getMinutes();
var second=d.getSeconds();
var week=d.getDay();
var sMyWeek=getweek(week);
var current_time=year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second+" "+sMyWeek;
return(current_time);
}
function getweek(week){
var myweek=["Sunday","Monday","Tuesday","Wednesday","Friday","Saturday"];
return(myweek[week]);
}
var Clock1;
function begin_click(){
if(Clock1 == undefined){
begin();
Clock1=setInterval(begin,1000);
}
}
function begin(){
var ret=document.getElementById("text_box");
var current_time=gettime();
ret.value=current_time;
console.log(current_time);
}
function end_click(){
clearInterval(Clock1);
var ret=document.getElementById("text_box");
ret.value=null;
Clock1=undefined;
}

</script>
</body>
</html>
 

程序运行后,点击屏幕上begin按钮,则开始动态显示日期和时间,间隔为1秒更新一次,若点击end按键则停止显示,并清空左边时间,如下图