实现数字自增 发表于 2019-05-15 | 分类于 前端 | 热度 ℃ 字数统计 575 | 阅读时长 2 项目中遇到需要实现数字自增的动画效果,怎么实现呢,少废话,show me the code js实现数字从0到num的自增动画1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>数字自动增加</title> </head> <body> <h1 id="time">0</h1> <script> //数字自增到某一值动画参数(目标元素,自定义配置) function NumAutoPlusAnimation(targetEle, options) { /*可以自己改造下传入的参数,按照自己的需求和喜好封装该函数*/ //不传配置就把它绑定在相应html元素的data-xxxx属性上吧 options = options || {}; var $this = document.getElementById(targetEle), time = options.time || $this.data('time'), //总时间--毫秒为单位 finalNum = options.num || $this.data('value'), //要显示的真实数值 regulator = options.regulator || 100, //调速器,改变regulator的数值可以调节数字改变的速度 step = finalNum / (time / regulator),/*每30ms增加的数值--*/ count = 0, //计数器 initial = 0; var timer = setInterval(function() { count = count + step; if(count >= finalNum) { clearInterval(timer); count = finalNum; } //t未发生改变的话就直接返回 //避免调用text函数,提高DOM性能 var t = Math.floor(count); if(t == initial) return; initial = t; $this.innerHTML = initial; }, 30); } NumAutoPlusAnimation("time", { time: 1500, num: 12000, regulator: 50 }) </script> </body></html> css实现1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>css实现数字自动增加</title> <style> /* 撑开高度 */.flip-number::before { content: 'a'; display: block; color: transparent;} /* 数字 */.flip-number::after { position: absolute; width: 100%; height: 100%; top: 0; left: 0; content: '0\A 1\A 2\A 3\A 4\A 5\A 6\A 7\A 8\A 9\A 10\A' attr(data-num); display: block; white-space: pre-line; text-align: center; animation: flipNumber cubic-bezier(.12,.78,.52,1.2) 1 .4s; animation-fill-mode: forwards; will-change: transform;}/* to中translateY的内容要跟数字个数对应上 */@keyframes flipNumber { from {transform: translateY(0%);} to {transform: translateY(-1100%);}} .flip-number { position: relative; overflow: hidden; display: inline-block;} /* custom styles */.flip-number { font-size: 60px; background: #f88; text-align: center; width: 140px;} </style> <title>Document</title></head><body> <!-- data-num个数就是最终想达到的个数 --> <span class="flip-number" data-num="10"></span></body></html> # javascript # 备忘 # css