在做效果的时候,想要表现一个数字数据的动态变化,例如金额增加,此时我们就可以使用数字翻牌器来表现。当然,你也可以使用其他效果来表现。
下面我们就来实现,注意一点:
- 数字的增加
<!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>Document</title>
<style>
.turnBox {
display: inline-block;
position: relative;
background: #999999;
}
.turnBox .title {
margin: 0;
margin-bottom: 5px;
font-size: 16px;
color: #fff;
}
.turnBox .prefix {
font-size: 16px;
color: gold;
}
.turnBox .suffix {
font-size: 14px;
color: gold;
}
.turnBox .number{
padding: 0 5px;
font-size: 32px;
font-weight: 600;
color: gold;
}
</style>
</head>
<body>
<script>
class TurnNumber {
constructor(turnObj) {
this.number = turnObj.number;
this.title = turnObj.title;
this.prefix = turnObj.prefix;
this.suffix = turnObj.suffix;
if(this.checkNum(this.number)){//is a number
this.turnfunc(this.number,this.title,this.prefix,this.suffix);
}else {//is not a number
console.log('is note a number');
}
}
//generate turnNumber
turnfunc(number,title,prefix,suffix) {
var html_turnBox = ''||undefined,
html_number = ''||undefined,
html_title = ''||undefined,
html_prefix = ''||undefined,
html_suffix = ''||undefined;
html_number = '<span class="number">0</span>';
html_prefix = '<span class="prefix">' prefix '</span>';
html_title = '<h3 class="title">' title '</h3>';
html_suffix = '<span class="suffix">' suffix '</span>';
html_turnBox = '<div class="turnBox">';
html_turnBox =html_title;
html_turnBox =html_prefix;
html_turnBox =html_number;
html_turnBox =html_suffix;
html_turnBox = '</div>';
document.body.innerHTML = html_turnBox;
var count = 0,
initial = 0,
step = number / 30;
var timer = setInterval(function(){
count =step;
if(count>=number){
clearInterval(timer);
count = number;
}
if(count==initial)return;
initial = parseInt(count);
document.getElementsByClassName('number')[0].innerHTML = initial;
},30);
}
checkNum(number) {
var re = /^[0-9] .?[0-9]*/;//whether is a number
if (!re.test(number)) {
return false;
}else {
if(typeof number === 'number'){
return true;
}else {
return false;
}
}
}
}
var turnnumber = new TurnNumber({
number:2056,
title:'这是一个标题这是一个标题',
prefix:'¥',
suffix:'元'
});
</script>
</body>
</html>
效果如图