效果图:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script> function showTime(){ var showT = document.getElementById("time"); var date = new Date(); var sx; //判断是哪个时间段,这里只简单判断了上午中午下午 if(date.getHours()<12){ sx = "上午"; }else if(date.getHours()==12){ sx = "中午"; }else if(date.getHours()>12){ sx = "下午"; } /*如果需要显示年月日也可插入以下代码: var s = date.getFullYear()+"-"+(date.getMonth()+1)+ "-"+date.getDate()+" "+ date.getHours()+":"+date.getMinutes()+ ":"+date.getSeconds(); */ var s = sx+date.getHours()+":"+date.getMinutes()+ ":"+date.getSeconds(); showT.innerHTML = s; } var flag = true;//判断时间是否停止 if(flag){ var t = window.setInterval("showTime()",1000); } function startTime(){ if(!flag){ flag = true; t = window.setInterval("showTime()",1000); } } function stopTime(){ if(flag){ flag = false; window.clearInterval(t); } } </script> </head> <body> <div id = "time"></div> <input type="button" value="开始" onclick="startTime()"/> <input type="button" value="停止" onclick="stopTime()"/> </body> </html>