时钟案例:
- html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>title>
- <style>
- div {
- width: 400px;
- height: 100px;
- background-color: #ccc;
- border: 1px solid #f00;
- margin: 130px auto;
- text-align: center;
- line-height: 100px;
- font-size: 24px;
- }
- style>
- head>
- <body>
- <div>div>
- body>
-
- <script>
- function dateTime() {
- //获取当前系统时间,并且拼接成“xxxx年xx月xx日 xx:xx:xx”的形式
- var date = new Date();
- console.log(date);
- //获取时分秒,如果时分秒是一位数字,给它拼接成两位数字
- var hour = date.getHours();
- if(hour<10){
- hour = '0'+hour;
- }
-
- var minutes = date.getMinutes();
- if(minutes<10){
- minutes ='0'+minutes;
- }
-
- var seconds =date.getSeconds();
- if(seconds<10){
- seconds = '0'+seconds;
- }
-
- var timeStr = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日 " + hour +
- ":" + minutes + ":" + seconds;
-
- //获取div元素,并将timeStr存储到div元素中
- var divEle = document.querySelector('div');
- divEle.innerHTML = timeStr;
- }
-
- //注意:setInterval(要调用的函数,间隔的毫秒是)里第一个参数如果不是直接定义的函数,而是调用其它的函数,只需要写函数名称,不要带()
- dateTime();
- setInterval(dateTime, 1000);
- script>
-
- html>
国庆倒计时案例:
- html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>title>
- <style>
- div{
- width: 600px;
- height: 200px;
- border: 1px solid black;
- margin: 150px auto;
- text-align: center;
- line-height: 200px;
- font-size: 24px;
- background-image: url(img/guoqin.jpg);
-
- }
- style>
- head>
- <body>
- <div> div>
- body>
- <script>
- function datetime(){
- var dateFur = new Date('2022','9','1');
- var fs = dateFur.getTime();
- console.log(dateFur);
- console.log(fs);
- var dateNow = new Date();
- var ns = dateNow.getTime();
- console.log(dateNow);
- console.log(ns);
-
- var time = fs - ns;
-
- console.log(time);
-
- days = parseInt(time/(24*60*60*1000));
- if(days<10){
- days = '0'+days;
- }
- hours = parseInt((time%(24*60*60*1000))/(60*60*1000));
- // console.log(hours);
- if(hours<10){
- hours = '0'+hours;
- }
- minutes = parseInt(((time%(24*60*60*1000))%(60*60*1000))/(60*1000));
- // console.log(minutes);
- if(minutes<10){
- minutes = '0'+minutes;
- }
- seconds = parseInt((((time%(24*60*60*1000))%(60*60*1000))%(60*1000))/1000);
- // console.log(seconds);
- if(seconds<10){
- seconds = '0'+seconds;
- }
- var timestr = "十一倒计时:"+days+"天"+hours+"时"+minutes+"分"+seconds+"秒";
- // console.log(timestr);
-
- var divEle = document.querySelector('div');
- divEle.innerHTML = timestr;
- }
-
- datetime();
- setInterval(datetime,1000);
-
- script>
- html>