使用onload和setTimeout、setInterval来实现当前的时间
1.在body里面使用onload和在函数中使用setTimeout来实现当前的日期时间不断变化
2.在script中直接是用setInterval实现当前实现的日期时间不断变化
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body onload="fun()"> <p id="demo"></p> <script> function fun() {var date=new Date(); var year=date.getFullYear(); var month=date.getMonth()+1;//这里用函数获取的日期是从0-11,所以要加1 var datte=date.getDate(); var hour=date.getHours(); var minute=date.getMinutes(); var second=date.getSeconds(); if(minute<10) minute="0"+minute; if(second<10) second="0"+second; document.getElementById("demo").innerHTML=year+"年"+month+"月"+datte+"日"+hour+":"+minute+":"+second; setTimeout("fun()",1); } </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body > <p id="demo"></p> <script> window.onload=fun();//单独这样写会更好 function fun() {var date=new Date(); var year=date.getFullYear(); var month=date.getMonth()+1; var datte=date.getDate(); var hour=date.getHours(); var minute=date.getMinutes(); var second=date.getSeconds(); if(minute<10) minute="0"+minute; if(second<10) second="0"+second; document.getElementById("demo").innerHTML=year+"年"+month+"月"+datte+"日"+hour+":"+minute+":"+second; setTimeout("fun()",1);//使用clearTimeout来清除 } </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body > <p id="demo"></p> <script> function fun() {var date=new Date(); var year=date.getFullYear(); var month=date.getMonth()+1; var datte=date.getDate(); var hour=date.getHours(); var minute=date.getMinutes(); var second=date.getSeconds(); if(minute<10) minute="0"+minute; if(second<10) second="0"+second; document.getElementById("demo").innerHTML=year+"年"+month+"月"+datte+"日"+hour+":"+minute+":"+second; } setInterval("fun()",1);//自动循环,使用clearInterval来清除 </script> </body> </html>
时间会变化,秒钟更为明显