效果:
body部分
<div id="counter">
<div></div>
</div>
css样式
<style>
body {
background: #f3f3f3;
}
#counter {
width: 100%;
height: 80px;
margin: 200px auto;
box-sizing: border-box;
padding-top: 10px;
position: relative;
left: -2px;
}
#counter div {
width: 660px;
margin: 0 auto;
background: #b2dbff;
color: #fff;
font-family: "微软雅黑";
padding-left: 3em;
border-radius: 20px;
box-sizing: border-box;
}
#counter div span {
font-size: 24px;
position: relative;
top: -3px;
}
#counter div .milk-num {
display: inline-block;
padding: 5px 15px;
background: #fff;
border-radius: 5px;
color: #e03d2e;
margin: 10px 5px;
font-size: 30px;
line-height: 36px;
font-weight: bold;
}
#counter div :nth-child(2) {
margin-left: 60px;
}
#counter div :last-child {
margin-left: 20px;
}
</style>
js部分
<script>
window.onload = function() {
var counter = document.getElementById('counter');
var count = 950; // 自定义起始数据
// 每个3秒自动增长5-9的随机数
setInterval(function() {
var random = 5 + Math.round(Math.random() * 4); // 生成5-9的随机数
count += random;
divideNumber(count);
}, 1000); //
}
// 整数拆分
function divideNumber(num) {
counter.getElementsByTagName('div')[0].innerHTML = "";
var arr = [];
var s = 0;
var item = "";
while (num > 0) {
arr[s] = num % 10;
num = Math.floor(num / 10);
s++;
}
for (var i = arr.length - 1; i >= 0; i--) {
item += "<p class='milk-num'>" + arr[i] + "</p>"
}
counter.getElementsByTagName('div')[0].innerHTML = "<span>目前已售出</span><p class='milk-num'>0</p>" + item + "<span>件</span>";
}
</script>