2023年跨年:炫彩烟花——HTML代码实现

*2022年圣诞节到来啦,很高兴这次我们又能一起度过~

📂文章目录

  • 前言
  • 效果展示
  • 一、夜景烟花绽放动画效果
  • HTML源码
  • 2023年(新年)春节倒计时代码
  • 源码
  • 2023除夕倒计时
  • 效果展示
  • 源码
  • 宇宙星空-效果展示
  • 1.源码
  • 2.思路
  • 3.步骤(js部分)
  • 更多干货🚀
  • 前言

    时光荏苒,白驹过隙。
    2022这一年又在忙碌中度过了,过去的一年,我们同努力,我们共欢笑,每一次成功都蕴藏着我们辛勤的劳动。
    新的一年即将来到,我们不能停滞不前,一味只是骄傲。愿大家与时俱进,拼搏不懈,共创新的辉煌!
    借着新年到来的喜庆,给大家分享一个新年烟花的前端代码,快拿着代码展示给你的朋友们看吧!!
    转眼间已经到了2022的尾巴,这一年对于国家来说丰富充实,冬奥会在北京举行、中国共产党第二十次全国代表大会召开、社会共同抗击疫情的第三年、我国完成天宫空间站建造……对于我们每一个个体,2022也承载着我们的快乐与悲伤,它是无法替代的。
    新的一年马上就要到了,让我们告别2022,迎接2023!
    希望2023,全糖去冰。

    效果展示

    一、夜景烟花绽放动画效果

    HTML源码

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
    	<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
    	<style>
    		body{margin:0;padding:0;overflow: hidden;}
    		.city{width:100%;position:fixed;bottom: 0px;z-index: 100;}
    		.city img{width: 100%;}
    	</style>
    	<title>html5夜景放烟花绽放动画效果</title>
    </head>
    <body onselectstart = "return false">
    
    <div style="height:700px;overflow:hidden;">
    
    	<canvas id='cas' style="background-color:rgba(0,5,24,1);">浏览器不支持canvas</canvas>
    	<div class="city"><img src="img/city.png" alt="" /></div>
    	<img src="img/moon.png" alt="" id="moon" style="visibility: hidden;"/>
    	<div style="display:none">
    		<div class="shape">新年快乐</div>
    		<div class="shape">合家幸福</div>
            <div class="shape">万事如意</div>
            <div class="shape">心想事成</div>
            <div class="shape">财源广进</div>
    	</div>
    	
    </div>
    	
    	<script>
    		var canvas = document.getElementById("cas");
    		var ocas = document.createElement("canvas");
    		var octx = ocas.getContext("2d");
    		var ctx = canvas.getContext("2d");
    		ocas.width = canvas.width = window.innerWidth;
    		ocas.height = canvas.height = 700;
    		var bigbooms = [];
    	
    		window.onload = function(){
    			initAnimate()
    		}
    
    		function initAnimate(){
    			drawBg();
    
    			lastTime = new Date();
    			animate();
    		}
    
    		var lastTime;
    		function animate(){
    			ctx.save();
    			ctx.fillStyle = "rgba(0,5,24,0.1)";
    			ctx.fillRect(0,0,canvas.width,canvas.height);
    			ctx.restore();
    
    
    			var newTime = new Date();
                if(newTime-lastTime>500+(window.innerHeight-767)/2){
    				var random = Math.random()*100>2?true:false;
    				var x = getRandom(canvas.width/5 , canvas.width*4/5);
    				var y = getRandom(50 , 200);
    				if(random){
    					var bigboom = new Boom(getRandom(canvas.width/3,canvas.width*2/3) ,2,"#FFF" , {x:x , y:y});
    					bigbooms.push(bigboom)
    				}
    				else {
    					var bigboom = new Boom(getRandom(canvas.width/3,canvas.width*2/3) ,2,"#FFF" , {x:canvas.width/2 , y:200} , document.querySelectorAll(".shape")[parseInt(getRandom(0, document.querySelectorAll(".shape").length))]);
    					bigbooms.push(bigboom)
    				}
    				lastTime = newTime;
    				console.log(bigbooms)
    			}
    
    			stars.foreach(function(){
    				this.paint();
    			})
    
    			drawMoon();
    
    			bigbooms.foreach(function(index){
    				var that = this;
    				if(!this.dead){
    					this._move();
    					this._drawLight();
    				}
    				else{
    					this.booms.foreach(function(index){
    						if(!this.dead) {
    							this.moveTo(index);
    						}
    						else if(index === that.booms.length-1){
    							bigbooms[bigbooms.indexOf(that)] = null;
    						}
    					})
    				}
    			});
    			
    			raf(animate);
    		}
    
    		function drawMoon(){
    			var moon = document.getElementById("moon");
    			var centerX = canvas.width-200 , centerY = 100 , width = 80;
    			if(moon.complete){
    				ctx.drawImage(moon , centerX , centerY , width , width )
    			}
    			else {
    				moon.onload = function(){
    					ctx.drawImage(moon ,centerX , centerY , width , width)
    				}
    			}
    			var index = 0;
    			for(var i=0;i<10;i++){
    				ctx.save();
    				ctx.beginPath();
    				ctx.arc(centerX+width/2 , centerY+width/2 , width/2+index , 0 , 2*Math.PI);
    				ctx.fillStyle="rgba(240,219,120,0.005)";
    				index+=2;
    				ctx.fill();
    				ctx.restore();
    			}
    			
    		}
    
    		Array.prototype.foreach = function(callback){
    			for(var i=0;i<this.length;i++){
    				if(this[i]!==null) callback.apply(this[i] , [i])
    			}
    		}
    
    		var raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); };
     		
    		canvas.onclick = function(){
    			var x = event.clientX;
    			var y = event.clientY;
    			var bigboom = new Boom(getRandom(canvas.width/3,canvas.width*2/3) ,2,"#FFF" , {x:x , y:y});
    			bigbooms.push(bigboom)
    		}
    
    		// canvas.addEventLisener("touchstart" , function(event){
    		// 	var touch = event.targetTouches[0];
    		// 	var x = event.pageX;
    		// 	var y = event.pageY;
    		// 	var bigboom = new Boom(getRandom(canvas.width/3,canvas.width*2/3) ,2,"#FFF" , {x:x , y:y});
    		// 	bigbooms.push(bigboom)
    		// })
    
    		var Boom = function(x,r,c,boomArea,shape){
    			this.booms = [];
    			this.x = x;
    			this.y = (canvas.height+r);
    			this.r = r;
    			this.c = c;
    			this.shape = shape || false;
    			this.boomArea = boomArea;
    			this.theta = 0;
    			this.dead = false;
    			this.ba = parseInt(getRandom(80 , 200));
    		}
    		Boom.prototype = {
    			_paint:function(){
    				ctx.save();
    				ctx.beginPath();
    				ctx.arc(this.x,this.y,this.r,0,2*Math.PI);
    				ctx.fillStyle = this.c;
    				ctx.fill();
    				ctx.restore();
    			},
    			_move:function(){
    				var dx = this.boomArea.x - this.x , dy = this.boomArea.y - this.y;
    				this.x = this.x+dx*0.01;
    				this.y = this.y+dy*0.01;
    
    				if(Math.abs(dx)<=this.ba && Math.abs(dy)<=this.ba){
    					if(this.shape){
    						this._shapBoom();
    					}
    					else this._boom();
    					this.dead = true;
    				}
    				else {
    					this._paint();
    				}
    			},
    			_drawLight:function(){
    				ctx.save();
    				ctx.fillStyle = "rgba(255,228,150,0.3)";
    				ctx.beginPath();
    				ctx.arc(this.x , this.y , this.r+3*Math.random()+1 , 0 , 2*Math.PI);
    				ctx.fill();
    				ctx.restore();
    			},
    			_boom:function(){
    				var fragNum = getRandom(30 , 200);
    				var style = getRandom(0,10)>=5? 1 : 2;
    				var color;
    				if(style===1){
    					color = {
    						a:parseInt(getRandom(128,255)),
    						b:parseInt(getRandom(128,255)),
    						c:parseInt(getRandom(128,255))
    					}
    				}
    
    				var fanwei = parseInt(getRandom(300, 400));
    				for(var i=0;i<fragNum;i++){
    					if(style===2){
    						color = {
    							a:parseInt(getRandom(128,255)),
    							b:parseInt(getRandom(128,255)),
    							c:parseInt(getRandom(128,255))
    						}
    					}
    					var a = getRandom(-Math.PI, Math.PI);
    					var x = getRandom(0, fanwei) * Math.cos(a) + this.x;
    					var y = getRandom(0, fanwei) * Math.sin(a) + this.y; 
    					var radius = getRandom(0 , 2)
    					var frag = new Frag(this.x , this.y , radius , color , x , y );
    					this.booms.push(frag);
    				}
    			},
    			_shapBoom:function(){
    				var that = this;
    				putValue(ocas , octx , this.shape , 5, function(dots){
    					var dx = canvas.width/2-that.x;
    					var dy = canvas.height/2-that.y;
    					for(var i=0;i<dots.length;i++){
    						color = {a:dots[i].a,b:dots[i].b,c:dots[i].c}
    						var x = dots[i].x;
    						var y = dots[i].y;
    						var radius = 1;
    						var frag = new Frag(that.x , that.y , radius , color , x-dx , y-dy);
    						that.booms.push(frag);
    					}
    				})
    			}
    		}
    
    		function putValue(canvas , context , ele , dr , callback){
    			context.clearRect(0,0,canvas.width,canvas.height);
    			var img = new Image();
    			if(ele.innerHTML.indexOf("img")>=0){
    				img.src = ele.getElementsByTagName("img")[0].src;
    				imgload(img , function(){
    					context.drawImage(img , canvas.width/2 - img.width/2 , canvas.height/2 - img.width/2);
    					dots = getimgData(canvas , context , dr);
    					callback(dots);
    				})
    			}
    			else {
    				var text = ele.innerHTML;
    				context.save();
    				var fontSize =200;
    				context.font = fontSize+"px 宋体 bold";
    				context.textAlign = "center";
    				context.textBaseline = "middle";
    				context.fillStyle = "rgba("+parseInt(getRandom(128,255))+","+parseInt(getRandom(128,255))+","+parseInt(getRandom(128,255))+" , 1)";
    				context.fillText(text , canvas.width/2 , canvas.height/2);
    				context.restore();
    				dots = getimgData(canvas , context , dr);
    				callback(dots);
    			}
    		}
    
    		function imgload(img , callback){
    			if(img.complete){
    				callback.call(img);
    			}
    			else {
    				img.onload = function(){
    					callback.call(this);
    				}
    			}
    		}
    
    		function getimgData(canvas , context , dr){
    			var imgData = context.getImageData(0,0,canvas.width , canvas.height);
    			context.clearRect(0,0,canvas.width , canvas.height);
    			var dots = [];
    			for(var x=0;x<imgData.width;x+=dr){
    				for(var y=0;y<imgData.height;y+=dr){
    					var i = (y*imgData.width + x)*4;
    					if(imgData.data[i+3] > 128){
    						var dot = {x:x , y:y , a:imgData.data[i] , b:imgData.data[i+1] , c:imgData.data[i+2]};
    						dots.push(dot);
    					}
    				}
    			}
    			return dots;
    		}
    
    		function getRandom(a , b){
    			return Math.random()*(b-a)+a;
    		}
    
    
    		var maxRadius = 1 , stars=[];
    		function drawBg(){
    			for(var i=0;i<100;i++){
    				var r = Math.random()*maxRadius;
    				var x = Math.random()*canvas.width;
    				var y = Math.random()*2*canvas.height - canvas.height;
    				var star = new Star(x , y , r);
    				stars.push(star);
    				star.paint()
    			}
    
    		}
    
    		var Star = function(x,y,r){
    			this.x = x;this.y=y;this.r=r;
    		}
    		Star.prototype = {
    			paint:function(){
    				ctx.save();
    				ctx.beginPath();
    				ctx.arc(this.x , this.y , this.r , 0 , 2*Math.PI);
    				ctx.fillStyle = "rgba(255,255,255,"+this.r+")";
    				ctx.fill();
    				ctx.restore();
    			}
    		}
    
    		var focallength = 250;
    		var Frag = function(centerX , centerY , radius , color ,tx , ty){
    			this.tx = tx;
    			this.ty = ty;
    			this.x = centerX;
    			this.y = centerY;
    			this.dead = false;
    			this.centerX = centerX;
    			this.centerY = centerY;
    			this.radius = radius;
    			this.color = color;
    		}
    
    		Frag.prototype = {
    			paint:function(){
    				ctx.save();
    				ctx.beginPath();
    				ctx.arc(this.x , this.y , this.radius , 0 , 2*Math.PI);
    				ctx.fillStyle = "rgba("+this.color.a+","+this.color.b+","+this.color.c+",1)";
    				ctx.fill()
    				ctx.restore();
    			},
    			moveTo:function(index){
    				this.ty = this.ty+0.3;
    				var dx = this.tx - this.x , dy = this.ty - this.y;
    				this.x = Math.abs(dx)<0.1 ? this.tx : (this.x+dx*0.1);
    				this.y = Math.abs(dy)<0.1 ? this.ty : (this.y+dy*0.1);
    				if(dx===0 && Math.abs(dy)<=80){
    					this.dead = true;
    				}
    				this.paint();
    			}
    		}
    	</script>
    
    </body>
    </html>
    
    

    再新建文件夹img把以下两张图片放进去

    city.png

    moon.png

    2023年(新年)春节倒计时代码

    2023年新年倒计时HTML源代码,2023年春节倒计时代码,直接运行index.html即可。

    源码

    NewYear.css

    /*初始化*/
    * {
      padding: 0;
      margin: 0 auto;
    }
    /*背景色*/
    body,
    html {
      background: url(./img/newyear.png) no-repeat;
      background-size: 100% 100%;
      background-attachment: fixed;
      /* background-color: black; */
    }
    /*父盒子*/
    .fa {
      color:#6c5ce7;
      margin-top: 200px;
      background-color: rgba(0, 17, 17, 0.5);
      /*边框圆角*/
      border-radius: 80px;
      /*伸缩布局*/
      display: flex;
      /*改变主轴方向  竖排*/
      flex-direction: column;
    }
    .fir {
      margin-left: 620px;
      margin-bottom: 100px;
      font-size: 80px;
    }
    .fa .sj {
      /*伸缩布局*/
      display: flex;
      /*改变主轴方向*/
      flex-direction: column;
    }
    .fa .sj div {
      width: 100%;
      /*伸缩布局*/
      display: flex;
      /*主轴排列方式*/
      justify-content: center;
      color: black;
      margin-bottom: 60px;
      /*多行侧轴排列方式*/
      align-content: space-around;
      color:#ff7675;
      font-size: 55px;
    }
    .fa .sj .zi {
      color:#d63031;
    }
    
    
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>新年倒计时</title>
        <link rel="stylesheet" href="NewYear.css">
        <script src="NewYear.js"></script>
    </head>
    <body>
        <div class="fa">
            <span class="fir">距离2023春节(1-22)还有</span>
            <div class="sj">
                <div><span></span><span class="zi">天</span></div>
                <div><span></span><span class="zi">时</span></div>
                <div><span></span><span class="zi">分</span></div>
                <div><span></span><span class="zi">秒</span></div>
            </div>
        </div>
    </body>
    </html>
    
    

    2023除夕倒计时

    效果展示

    源码

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>新年快乐</title>
    <style>
    body{
      overflow: hidden;
      margin: 0;
    }
    h1{
      position: fixed;
      top: 30%;
      left: 0;
      width: 100%;
      text-align: center;
      transform:translateY(-50%);
      font-family: 'Love Ya Like A Sister', cursive;
      font-size: 60px;
      color: #c70012;
      padding: 0 20px;
    }
    h1 span{
      position: fixed;
      left: 0;
      width: 100%;
      text-align: center;
      margin-top:30px;
      font-size:40px;
    }
    </style>
     
    </head>
    <body>
    <h1 id="h1"></h1>
    <canvas></canvas>
     
    <script>
    var canvas = document.querySelector("canvas"),
      ctx = canvas.getContext("2d");
     
    var ww,wh;
     
    function onResize(){
      ww = canvas.width = window.innerWidth;
      wh = canvas.height = window.innerHeight;
    }
     
    ctx.strokeStyle = "pink";
    ctx.shadowBlur = 25;
    ctx.shadowColor = "hsla(0, 100%, 60%,0.5)";
     
    var precision = 100;
    var hearts = [];
    var mouseMoved = false;
    function onMove(e){
      mouseMoved = true;
      if(e.type === "touchmove"){
        hearts.push(new Heart(e.touches[0].clientX, e.touches[0].clientY));
        hearts.push(new Heart(e.touches[0].clientX, e.touches[0].clientY));
      }
      else{
        hearts.push(new Heart(e.clientX, e.clientY));
        hearts.push(new Heart(e.clientX, e.clientY));
      }
    }
     
    var Heart = function(x,y){
      this.x = x || Math.random()*ww;
      this.y = y || Math.random()*wh;
      this.size = Math.random()*2 + 1;
      this.shadowBlur = Math.random() * 10;
      this.speedX = (Math.random()+0.2-0.6) * 8;
      this.speedY = (Math.random()+0.2-0.6) * 8;
      this.speedSize = Math.random()*0.05 + 0.01;
      this.opacity = 1;
      this.vertices = [];
      for (var i = 0; i < precision; i++) {
        var step = (i / precision - 0.5) * (Math.PI * 2);
        var vector = {
          x : (15 * Math.pow(Math.sin(step), 3)),
          y : -(13 * Math.cos(step) - 5 * Math.cos(2 * step) - 2 * Math.cos(3 * step) - Math.cos(4 * step))
        }
        this.vertices.push(vector);
      }
    }
     
    Heart.prototype.draw = function(){
      this.size -= this.speedSize;
      this.x += this.speedX;
      this.y += this.speedY;
      ctx.save();
      ctx.translate(-1000,this.y);
      ctx.scale(this.size, this.size);
      ctx.beginPath();
      for (var i = 0; i < precision; i++) {
        var vector = this.vertices[i];
        ctx.lineTo(vector.x, vector.y);
      }
      ctx.globalAlpha = this.size;
      ctx.shadowBlur = Math.round((3 - this.size) * 10);
      ctx.shadowColor = "hsla(0, 100%, 60%,0.5)";
      ctx.shadowOffsetX = this.x + 1000;
      ctx.globalCompositeOperation = "screen"
      ctx.closePath();
      ctx.fill()
      ctx.restore();
    };
     
     
    function render(a){
      requestAnimationFrame(render);
     
      hearts.push(new Heart())
      ctx.clearRect(0,0,ww,wh);
      for (var i = 0; i < hearts.length; i++) {
        hearts[i].draw();
        if(hearts[i].size <= 0){
          hearts.splice(i,1);
          i--;
        }
      }
    }
     
     
    onResize();
    window.addEventListener("mousemove", onMove);
    window.addEventListener("touchmove", onMove);
    window.addEventListener("resize", onResize);
    requestAnimationFrame(render);
     
    window.onload=function starttime(){
            time(h1,'2023/1/21');     // 2023年春节时间
            ptimer = setTimeout(starttime,1000); // 添加计时器
    }
     
        function time(obj,futimg){
            var nowtime = new Date().getTime(); // 现在时间转换为时间戳
            var futruetime =  new Date(futimg).getTime(); // 未来时间转换为时间戳
            var msec = futruetime-nowtime; // 毫秒 未来时间-现在时间
            var time = (msec/1000);  // 毫秒/1000
            var day = parseInt(time/86400); // 天  24*60*60*1000
            var hour = parseInt(time/3600)-24*day;    // 小时 60*60 总小时数-过去的小时数=现在的小时数
            var minute = parseInt(time%3600/60); // 分 -(day*24) 以60秒为一整份 取余 剩下秒数 秒数/60 就是分钟数
            var second = parseInt(time%60);  // 以60秒为一整份 取余 剩下秒数
            obj.innerHTML="<br>2023年<br>除夕倒计时:<br>"+day+"天"+hour+"小时"+minute+"分"+second+"秒"+"<br><span>善良 勇敢 优秀 决不妥协<br>祝你也祝我<br>"
            return true;
        }
    </script>
      <audio id="bgmusic" src="http://music.163.com/song/media/outer/url?id=1851244378.mp3" autoplay="autoplay" loop="loop" style="display: block; width: 3%; height:3%;"></audio>
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function () {
                function audioAutoPlay() {
                    var audio = document.getElementById('bgmusic');
                    audio.play();
                    document.addEventListener("WeixinJSBridgeReady", function () {
                        audio.play();
                        }, false);
                     }
                     audioAutoPlay();
                     });
    </script>
    </body>
    </html>
    

    宇宙星空-效果展示


    距离2023.1.1还有27天(天数我是乱写的,并不是按照文章发布时间来写的,大家可以自己修改源码)

    1.源码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
     
     
        <script>
            var count = document.getElementsByClassName('main');
            var times0 = document.getElementsByClassName('time');
            var inputtime = +new Date("2023/01/01 00:00:00");
            console.log(inputtime);
     
            var timer = null;
            clearInterval(timer)
            timer = setInterval(countdown,1000)
     
     
            function countdown(){
                var nowtime = +new Date();
                
                var times = parseInt((inputtime - nowtime ) / 1000);
                
                if(times >= 0){
                         
                var d = parseInt(times/60/60/24);
                d = d < 10 ? '0' + d : d ;
     
                var h = parseInt(times/60 /60%24);
                h = h < 10 ? '0' + h : h ;
     
               var m = parseInt(times/60%60);
                m = m < 10 ? '0' + m : m ;
     
                var s = parseInt(times%60);
                s = s < 10 ? '0' + s : s ;
     
                times0[0].innerHTML = d;
                times0[1].innerHTML = h;
                times0[2].innerHTML = m;
                times0[3].innerHTML = s;
                }else{
                    clearInterval(timer)
                }
             }               
        </script>
     
     
        <style>
            *{
                margin: 0%;
                padding: 0%;
            }
     
            body{
                height: 100vh;
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .block{
                display: inline-block;
                margin-left: 50px;
            }
            .block p{
                font-size: 40px;
                color: aliceblue;
                font-weight: bolder;
                text-align: center;
            }
            .block a{
                font-size: 20px;
                color: aliceblue;
            }
            #nyc{
                color: aliceblue;
                font-size: 50px;
            }
     
        </style>
    </head>
     
     
    <body background="图片\10523Q492-0.jpg">
        <div class="main">
            <p id="nyc"> New Year Countdown</p>
            <br>
            
            <div class="block">
                <p class="time">00</p>
                <a>days</a>
            </div>
            <div class="block">
                <p class="time">00</p>
                <a>hours</a>
            </div>
            <div class="block">
                <p class="time">00</p>
                <a>minutes</a>
            </div>
            <div class="block">
                <p class="time">00</p>
                <a>seconds</a>
            </div>
        </div>    
    </body>
     
     
    </html>
    

    2.思路

    创建一个计时器函数, 计算出当前时间和目标时间的距离.

    利用"setInterval"方法不断调用计时器函数,达到数字变换, 也就是倒计时的效果.

    3.步骤(js部分)

             var count = document.getElementsByClassName('main');
             var times0 = document.getElementsByClassName('time');
            
             var inputtime = +new Date("2023/01/01 00:00:00");
             var nowtime = +new Date();
             console.log(inputtime);
     
             var timer = null;
             clearInterval(timer)
             timer = setInterval(countdown,1000)
    

    A."var"定义变量
    利用"document.getElementsByClassName()"方法提取中已经创建的元素作为js对象.
    类似的方法有:


    B. 获取时间

    "+new Date()"方法可以获取当前时间距离"1970年1月1日0时0分0秒’的毫秒数, 利用这点可以获取当前时间.
    括号中若添加具体日期(写法: 年/月/日 时:分:秒 ), 则可以获取具体日期距离"1970年1月1日0时0分0秒’的毫秒数, 利用这点可以获取目标时间.

    function countdown(){
                
                var times = parseInt((inputtime - nowtime ) / 1000);
                
                if(times >= 0){
                var d = parseInt(times/60/60/24);
                d = d < 10 ? '0' + d : d ;
     
                var h = parseInt(times/60 /60%24);
                h = h < 10 ? '0' + h : h ;
     
               var m = parseInt(times/60%60);
                m = m < 10 ? '0' + m : m ;
     
                var s = parseInt(times%60);
                s = s < 10 ? '0' + s : s ;
     
                times0[0].innerHTML = d;
                times0[1].innerHTML = h;
                times0[2].innerHTML = m;
                times0[3].innerHTML = s;
                }else{
                    clearInterval(timer)
                }
            }
    

    C.创建计时器函数
    计算时间的距离:
    (目标时间-当前时间)/1000=时间距离

     var times = parseInt((inputtime - nowtime ) / 1000);
    

    时间距离转换成 天数,时数,分数,秒数:
    并做一个简单判断:
    如果计算出来的数字小于10, 则在数字面前添加一个0一保持美观和谐.

    var d = parseInt(times/60/60/24);
                d = d < 10 ? '0' + d : d ;
     
                var h = parseInt(times/60 /60%24);
                h = h < 10 ? '0' + h : h ;
     
               var m = parseInt(times/60%60);
                m = m < 10 ? '0' + m : m ;
     
                var s = parseInt(times%60);
                s = s < 10 ? '0' + s : s ;
    

    将计算所得数字添加到页面中:

    利用到了 "innerhtml"方法, 主要用于改变中已经定义的元素.
    最后做一个总的判断:
    如果时间距离大于零, 则做计算, 展现倒计时效果.
    如果距离等于零, 则对函数的反复调用停止, 计时终止

    if(times >= 0){
     
     
     
     }else{
     clearInterval(timer)
                }
    

    D.反复调用计时器函数

            var timer = null;
            clearInterval(timer)
            timer = setInterval(countdown,1000)
    
            var timer = null;
            clearInterval(timer)
            timer = setInterval(countdown,1000)
    

    "setInterval()"方法中有两个参数:
    第一个: 将要调用的函数名;
    第二个: 调用的间隔时间, 单位为一毫秒, 自然, “1000"即代表"1秒钟调用一次”
    "clearInterval(timer)"指在调用之前将调用器归零


    更多干货🚀

    1. 如果我的博客对你有帮助、如果你喜欢我的博客内容,请 “👍点赞” “✍️评论” “💙收藏” 一键三连哦!
    2. 💗【👇🏻👇🏻👇🏻关注我| 💬获取更多源码 | 优质文章】 带您学习各种前端插件、3D炫酷效果、图片展示、文字效果、以及整站模板 、大学生毕业HTML模板 、期末大作业模板 、等! 「在这里有好多
      前端 开发者,一起探讨 前端 Node 知识,互相学习」!

    物联沃分享整理
    物联沃-IOTWORD物联网 » 2023年跨年:炫彩烟花——HTML代码实现

    发表评论