Home > Web Front-end > JS Tutorial > body text

How to use JavaScript to create a dynamic clock

一个新手
Release: 2017-09-26 10:02:28
Original
3132 people have browsed it

1:clock.js

/** *  动态显示当前时间 */function showDateTime(){    
var sWeek=new Array("日","一","二","三","四","五","六");  //声明数组存储一周七天    
var myDate=new Date(); //获取当天日期    
var sYear=myDate.getFullYear(); //获取年    
var sMonth=myDate.getMonth()+1; //获取月    
var sDate=myDate.getDate(); //获取日    
var sDay=sWeek[myDate.getDay()]; //根据得到的数字星期,利用数组转化为星期    
var h=myDate.getHours(); //获取小时    
var m=myDate.getMinutes(); //获取分钟    
var s=myDate.getSeconds(); //获取秒    //输入日期和星期    
document.getElementById("date").innerHTML=(sYear+"年"+sMonth+"月"+sDate+"日"+"星期"+sDay+"<br/>");    h = formatTwoDigits(h);  //格式化小时,如果不足两位在前面补0    m = formatTwoDigits(m); //格式化分钟,如果不足两位在前面补0    s = formatTwoDigits(s); //格式化秒钟后,如果不足两位在前面补0    //显示时间    document.getElementById("msg").innerHTML=(h+":"+m+":"+s+"<br/>");    setTimeout("showDateTime()",1000);//每秒执行一次showDateTime函数}window.onload=showDateTime;//在整个页面加载完成后执行此函数//如果输入数是一位数,则在十位上补0function formatTwoDigits(s) {    if (s<10)        return "0"+s;    else        return s;
}
Copy after login

2:clock.html

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>制作动态时钟</title>
    <script type="text/javascript" src="clock.js"></script></head><body>
    <h1 id="date"></h1>
    <span id="msg" style="font-size: 30px;background-color: greenyellow;">
    </span>
  </body>
</html>
Copy after login

The above is the detailed content of How to use JavaScript to create a dynamic clock. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!