一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服務器之家 - 編程語言 - JavaScript - js教程 - JavaScript實現消消樂的源代碼

JavaScript實現消消樂的源代碼

2021-12-30 16:46代碼100分 js教程

這篇文章主要介紹了JavaScript實現消消樂-源代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下

JavaScript實現消消樂的源碼下載地址:點擊下載源代碼

JavaScript實現消消樂的源代碼

index.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>LuckyStar</title>
        <link rel="stylesheet" href="./css/index.css?v=1.0.0" rel="external nofollow" >
    </head>
    <body>
        <div class="lucky-star" id="luckyStar">
            <div class="score-target">
                <p class="score-level">關卡 <span id="scoreLevel"></span></p>
                <p>目標:<span id="scoreTarget"></span></p>
            </div>
            <div class="score-current">得分<span id="scoreCurrent"></span></div>
            <div class="score-select" id="scoreSelect"></div>
            <ul class="star-list" id="starList"> </ul>
        </div>
    </body>
    <script src="./js/countUp.js"></script>
    <script src="./js/index.js"></script>
    <script src="./js/resize.js"></script>
    <script>
        new PopStar()
    </script>
</html>

JS文件

JavaScript實現消消樂的源代碼

main.js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
(function() {
    //全局配置
    var config = {
        tileWidth: .75, //小星星的寬高
        tileHeight: .75,
        tileSet: [], //存儲小星星的二維數組
        tableRows: 10, //行數
        baseScore: 5, //每一個小星星的基礎分數
        stepScore: 10, //每一個小星星的遞增分數
        targetScore: 2000, //目標分數,初始為2000
        el: document.querySelector('#starList'),// 星星列表
        scoreTarget: document.querySelector('#scoreTarget'),//目標分數
        scoreCurrent: document.querySelector('#scoreCurrent'),//當前分數
        scoreSelect: document.querySelector('#scoreSelect'),//選中星星分數
        scoreLevel: document.querySelector('#scoreLevel'),//當前所在的關數
    };
    //全局計算屬性
    var computed = {
        flag: true, //鎖
        choose: [], //已選中的小星星集合
        timer: null,
        totalScore: 0, //總分數
        tempTile: null,
        level: 1, //當前所在的關數(每闖過一關+1,游戲失敗回復為1)
        stepTargetScore: 1000, //闖關成功的遞增分數(1000/關)
        score: 0 //當前的計算分數
    };
 
    //Block對象
    function Block(number, row, col) {
        var tile = document.createElement('li');
        tile.width = config.tileWidth;
        tile.height = config.tileHeight;
        tile.number = number;
        tile.row = row;
        tile.col = col;
        return tile;
    }
 
    //入口函數
    function PopStar() {
        return new PopStar.prototype.init();
    }
 
    //PopStar原型
    PopStar.prototype = {
        /**
         * PopStar的入口函數
         */
        init: function() {
            this.initTable();
        },
        /**
         * 初始化操作
         */
        initTable: function() {
            this.initScore();
            this.initTileSet();
            this.initBlocks();
        },
 
        /**
         * 初始化當前分數和目標
         */
        initScore: function() {
            new CountUp(config.scoreTarget, config.targetScore, config.targetScore).start();
            config.scoreCurrent.innerHTML = computed.totalScore;
            config.scoreLevel.innerHTML = computed.level;
        },
        /**
         * 點擊事件操作
         */
        mouseClick: function() {
            var tileSet = config.tileSet,
                choose = computed.choose,
                baseScore = config.baseScore,
                stepScore = config.stepScore,
                el = config.el,
                self = this,
                len = choose.length;
            if (!computed.flag || len <= 1) {
                return;
            }
            computed.flag = false;
            computed.tempTile = null;
            var score = 0;
            for (var i = 0; i < len; i++) {
                score += baseScore + i * stepScore;
            }
 
            new CountUp(config.scoreCurrent, computed.totalScore, computed.totalScore += score).start();
            for (var i = 0; i < len; i++) {
                setTimeout(function(i) {
                    tileSet[choose[i].row][choose[i].col] = null;
                    el.removeChild(choose[i]);
                }, i * 100, i);
            }
            setTimeout(function() {
                self.move();
                //判斷結束
                setTimeout(function() {
                    if (self.isFinish()) {
                        self.clear();
                        if (computed.totalScore >= config.targetScore) {
                            new CountUp(config.scoreTarget, config.targetScore, config.targetScore += (computed.level - 1) * computed
                                    .stepTargetScore)
                                .start();
 
                            new CountUp(config.scoreLevel, computed.level, computed.level += 1).start();
                            alert("恭喜獲勝");
                            console.log("恭喜獲勝")
                        } else {
                            config.targetScore = config.scoreTarget = 2000;
                            computed.level = computed.totalScore = 0;
                            alert("游戲失敗");
                            console.log("游戲失敗")
                        }
                        computed.flag = true;
                        
                    } else {
                        choose = [];
                        computed.flag = true; //在所有動作都執行完成之后釋放鎖
                        self.mouseOver(computed.tempTile);
                    }
                }, 300 + choose.length * 150);
            }, choose.length * 100);
        },
        /**
         * 闖關成功或失敗清除(清除二維數組和el的子節點)操作
         */
        clear: function() {
            var tileSet = config.tileSet,
                rows = tileSet.length,
                el = config.el;
            var temp = [];
            for (var i = rows - 1; i >= 0; i--) {
                for (var j = tileSet[i].length - 1; j >= 0; j--) {
                    if (tileSet[i][j] === null) {
                        continue;
                    }
                    temp.push(tileSet[i][j])
                    tileSet[i][j] = null;
                }
            }
            for (var k = 0; k < temp.length; k++) {
                setTimeout(function(k) {
                    el.removeChild(temp[k]);   
                        if(k>=temp.length-1){
                                setTimeout(function(k) {
                                        new PopStar();
                                },1000)
                        }
                }, k * 100, k);
            }
        },
        /**
         * 是否游戲結束
         * @returns {boolean}
         */
        isFinish: function() {
            var tileSet = config.tileSet,
                rows = tileSet.length;
            for (var i = 0; i < rows; i++) {
                var row = tileSet[i].length;
                for (var j = 0; j < row; j++) {
                    var temp = [];
                    this.checkLink(tileSet[i][j], temp);
                    if (temp.length > 1) {
                        return false;
                    }
                }
            }
            return true;
        },
        /**
         * 消除星星后的移動操作
         */
        move: function() {
            var rows = config.tableRows,
                tileSet = config.tileSet;
            //向下移動
            for (var i = 0; i < rows; i++) {
                var pointer = 0; //pointer指向小方塊,當遇到null的時候停止,等待上面的小方塊落到這里來
                for (var j = 0; j < rows; j++) {
                    if (tileSet[j][i] != null) {
                        if (j !== pointer) {
                            tileSet[pointer][i] = tileSet[j][i];
                            tileSet[j][i].row = pointer;
                            tileSet[j][i] = null;
                        }
                        pointer++;
                    }
                }
            }
            //橫向移動(最下面一行其中有無空列)
            for (var i = 0; i < tileSet[0].length;) {
                if (tileSet[0][i] == null) {
                    for (var j = 0; j < rows; j++) {
                        tileSet[j].splice(i, 1);
                    }
                    continue;
                }
                i++;
            }
            this.refresh()
        },
        /**
         * 鼠標移入時的閃爍操作
         * @param obj
         */
        mouseOver: function(obj) {
            if (!computed.flag) { //處于鎖定狀態不允許有操作
                computed.tempTile = obj;
                return;
            }
            this.clearFlicker();
            var choose = [];
            this.checkLink(obj, choose);
            computed.choose = choose;
            if (choose.length <= 1) {
                choose = [];
                return;
            }
            this.flicker(choose);
            this.computeScore(choose);
        },
        /**
         * 計算已選中的星星分數
         * @param arr
         */
        computeScore: function(arr) {
            var score = 0,
                len = arr.length,
                baseScore = config.baseScore,
                stepScore = config.stepScore;
            for (var i = 0; i < len; i++) {
                score += baseScore + i * stepScore
            }
            if (score <= 0) {
                return;
            }
            computed.score = score;
            config.scoreSelect.style.opacity = '1';
            config.scoreSelect.innerHTML = arr.length + "連消 " + score + "分";
            setTimeout(function() {
                config.scoreSelect.style.opacity = '0';
            }, 1200)
        },
        /**
         * 鼠標移出時的消除星星閃爍的操作
         */
        clearFlicker: function() {
            var tileSet = config.tileSet;
            for (var i = 0; i < tileSet.length; i++) {
                for (var j = 0; j < tileSet[i].length; j++) {
                    var div = tileSet[i][j];
                    if (div === null) {
                        continue;
                    }
                    div.classList.remove("scale");
                }
            }
        },
        /**
         * 星星閃爍
         * @param arr
         */
        flicker: function(arr) {
            for (var i = 0; i < arr.length; i++) {
                var div = arr[i];
                div.classList.add("scale");
            }
        },
        /**
         * 檢查鼠標移入的這個星星是否有相連著的相同的星星,
         * @param obj star
         * @param arr choose
         */
        checkLink: function(obj, arr) {
            if (obj === null) {
                return;
            }
            arr.push(obj);
            /**
             * 檢查左邊方塊是否可以加入到選入的可消除星星行列:
             * 選中的星星不能是最左邊的,
             * 選中的星星左邊要有星星,
             * 選中的星星左邊的星星的跟選中的星星一樣,
             * 選中的星星左邊的星星沒有被選中過
             */
            var tileSet = config.tileSet,
                rows = config.tableRows;
            if (obj.col > 0 && tileSet[obj.row][obj.col - 1] && tileSet[obj.row][obj.col - 1].number === obj.number && arr.indexOf(
                    tileSet[obj.row][obj.col - 1]) === -1) {
                this.checkLink(tileSet[obj.row][obj.col - 1], arr);
            }
            if (obj.col < rows - 1 && tileSet[obj.row][obj.col + 1] && tileSet[obj.row][obj.col + 1].number === obj.number &&
                arr.indexOf(tileSet[obj.row][obj.col + 1]) === -1) {
                this.checkLink(tileSet[obj.row][obj.col + 1], arr);
            }
            if (obj.row < rows - 1 && tileSet[obj.row + 1][obj.col] && tileSet[obj.row + 1][obj.col].number === obj.number &&
                arr.indexOf(tileSet[obj.row + 1][obj.col]) === -1) {
                this.checkLink(tileSet[obj.row + 1][obj.col], arr);
            }
            if (obj.row > 0 && tileSet[obj.row - 1][obj.col] && tileSet[obj.row - 1][obj.col].number === obj.number && arr.indexOf(
                    tileSet[obj.row - 1][obj.col]) === -1) {
                this.checkLink(tileSet[obj.row - 1][obj.col], arr);
            }
        },
        /**
         * 初始化二維數組
         */
        initTileSet: function() {
            var rows = config.tableRows,
                arr = config.tileSet;
            for (var i = 0; i < rows; i++) {
                arr[i] = [];
                for (var j = 0; j < rows; j++) {
                    arr[i][j] = [];
                }
            }
        },
        /**
         * 初始化el的子節點
         */
        initBlocks: function() {
            var tileSet = config.tileSet,
                self = this,
                el = config.el,
                cols = tileSet.length;
            for (var i = 0; i < cols; i++) {
                var rows = tileSet[i].length;
                for (var j = 0; j < rows; j++) {
                    var tile = this.createBlock(Math.floor(Math.random() * 5), i, j);
                    tile.onmouseover = function() {
                        self.mouseOver(this)
                    };
                    tile.onclick = function() {
                        self.mouseClick();
                    };
                     
                    tileSet[i][j] = tile;
                    el.appendChild(tile);
                }
            }
            this.refresh()
        },
        /**
         * 渲染el的子節點
         */
        refresh: function() {
            var tileSet = config.tileSet;
            for (var i = 0; i < tileSet.length; i++) {
                var row = tileSet[i].length;
                for (var j = 0; j < row; j++) {
                    var tile = tileSet[i][j];
                    if (tile == null) {
                        continue;
                    }
                    tile.row = i;
                    tile.col = j;
                    tile.style.left = tileSet[i][j].col * config.tileWidth + "rem";
                    tile.style.bottom = tileSet[i][j].row * config.tileHeight + "rem";
                    tile.style.backgroundImage = "url('./images/" + tileSet[i][j].number + ".png')";
 
                }
            }
        },
        /**
         * 創建星星子節點的函數
         * @param number
         * @param row
         * @param col
         * @returns {HTMLElement}
         */
        createBlock: function(number, row, col) {
            return new Block(number, row, col);
        },
 
    };
    PopStar.prototype.init.prototype = PopStar.prototype;
    window.PopStar = PopStar;
})();

index.js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
(function()
{function u(a,b,c)
{
var d=document.createElement("li");
d.width=e.tileWidth;d.height=e.tileHeight;
d.number=a;
d.row=b;d.col=c;return d}
function m()
{return new m.prototype.init
}
var e={tileWidth:.75,tileHeight:.75,tileSet: [],
tableRows:10,baseScore:5,
stepScore:10,
targetScore:2E3,
el:document.querySelector("#starList"),
scoreTarget:document.querySelector("#scoreTarget"),
scoreCurrent:document.querySelector("#scoreCurrent"),
scoreSelect:document.querySelector("#scoreSelect"),
scoreLevel:document.querySelector("#scoreLevel")
},
n=!0,t=[],p=0,r=null,q=1;
m.prototype={
init:function(){this.initTable()
}
,initTable:function(){
this.initScore();
this.initTileSet();
this.initBlocks()
}
,
initScore:function(){
(new CountUp(e.scoreTarget,e.targetScore,e.targetScore)).start();
e.scoreCurrent.innerHTML=p;e.scoreLevel.innerHTML=q
},
mouseClick:function(){
var a=e.tileSet,b=t,c=e.baseScore,d=e.stepScore,f=e.el,g=this,h=b.length;if(n&&!(1>=h)){
n=!1;r=null;
for(var l=0,k=0;
k<h;k++)l+=c+k*d;(new CountUp(e.scoreCurrent,p,p+=l)).start();
for(k=0;k<h;k++)
setTimeout(function(c){a[b[c].row][b[c].col]=
null;
f.removeChild(b[c])},100*k,k);
setTimeout(function(){g.move();
setTimeout(function()
{g.isFinish()?(g.clear(),p>=e.targetScore?((new CountUp(e.scoreTarget,e.targetScore,e.targetScore+=1E3*(q-1))).start(),(new CountUp(e.scoreLevel,q,q+=1)).start(),alert("\u606d\u559c\u83b7\u80dc"),console.log("\u606d\u559c\u83b7\u80dc")):(e.targetScore=e.scoreTarget=2E3,q=p=0,alert("\u6e38\u620f\u5931\u8d25"),console.log("\u6e38\u620f\u5931\u8d25")),n=!0):(b=[],n=!0,g.mouseOver(r))},300+150*b.length)},100*b.length)}},
clear:function()
{for(var a=e.tileSet,b=e.el,c=[],
d=a.length-1;0<=d;d--)
for(var f=a[d].length-1;0<=f;f--)
null!==a[d][f]&&(c.push(a[d][f]),a[d][f]=null);
 
for(a=0;a<c.length;a++)
setTimeout(function(a)
{b.removeChild(c[a]);
a>=c.length-1&&setTimeout(function(a){new m},1E3)},100*a,a)},isFinish:function()
{for(var a=e.tileSet,b=a.length,c=0;c<b;c++)
for(var d=a[c].length,f=0;f<d;f++)
{var g=[];this.checkLink(a[c][f],g);
if(1<g.length)
return!1}return!0},
move:function()
{for(var a=e.tableRows,b=e.tileSet,c=0;
c<a;c++)for(var d=
0,f=0;f<a;f++)null!=b[f][c]&&(f!==d&&(b[d][c]=b[f][c],b[f][c].row=d,b[f][c]=null),d++);
for(c=0;c<b[0].length;
)if(null==b[0][c])
for(f=0;f<a;f++)b[f].splice(c,1);else c++;this.refresh()},
mouseOver:function(a){if(n)
{this.clearFlicker();
var b=[];
this.checkLink(a,b);
t=b;1>=b.length||(this.flicker(b),this.computeScore(b))}
else r=a
},
computeScore:function(a)
{for(var b=0,c=a.length,d=e.baseScore,f=e.stepScore,g=0;
g<c;g++)b+=d+g*f;
0>=b||(e.scoreSelect.style.opacity="1",e.scoreSelect.innerHTML=a.length+"\u8fde\u6d88 "+
b+"\u5206",setTimeout(function(){
e.scoreSelect.style.opacity="0"},1200))
},clearFlicker:function(){
for(var a=e.tileSet,b=0;b<a.length;b++)
for(var c=0;c<a[b].length;c++){var d=a[b][c];null!==d&&d.classList.remove("scale")}},flicker:function(a){for(var b=0;b<a.length;b++)a[b].classList.add("scale")
},
checkLink:function(a,b){
if(null!==a){
b.push(a);var c=e.tileSet,d=e.tableRows;0<a.col&&c[a.row][a.col-1]&&c[a.row][a.col-1].number===a.number&&-1===b.indexOf(c[a.row][a.col-1])&&this.checkLink(c[a.row][a.col-
1],b);a.col<d-1&&c[a.row][a.col+1]&&c[a.row]
[a.col+1].number===a.number&&-1===b.indexOf(c[a.row][a.col+1])&&this.checkLink(c[a.row][a.col+1],b);a.row<d-1&&c[a.row+1][a.col]&&c[a.row+1][a.col].number===a.number&&-1===b.indexOf(c[a.row+1][a.col])&&this.checkLink(c[a.row+1][a.col],b);0<a.row&&c[a.row-1][a.col]&&c[a.row-1][a.col].number===a.number&&-1===b.indexOf(c[a.row-1][a.col])&&this.checkLink(c[a.row-1][a.col],b)}},
initTileSet:function(){
for(var a=e.tableRows,b=e.tileSet,c=0;c<a;c++){b[c]=[];
for(var d= 0;d<a;d++)b[c][d]=[]}},
initBlocks:function()
{
for(var a=e.tileSet,b=this,c=e.el,d=a.length,f=0;f<d;f++)
for(var g=a[f].length,h=0;h<g;h++){
var l=this.createBlock(Math.floor(5*Math.random()),f,h);
l.onmouseover=function(){b.mouseOver(this)};
l.onclick=function(){b.mouseClick()};
a[f][h]=l;
c.appendChild(l)}
this.refresh()},
refresh:function()
{for(var a=e.tileSet,b=0;b<a.length;b++)
for(var c=a[b].length,d=0;d<c;d++)
{var f=a[b][d];
null!=f&&(f.row=b,f.col=d,f.style.left=a[b][d].col*e.tileWidth+"rem",f.style.bottom=
a[b][d].row*e.tileHeight+"rem",f.style.backgroundImage="url('./images/"+a[b][d].number+".png')")
}
}
,createBlock:function(a,b,c){return new u(a,b,c)
}
}
;m.prototype.init.prototype=m.prototype;window.PopStar=m
})();

resize.js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// JavaScript Document
(function px2rem(doc, win) {
  var docEl = doc.documentElement,
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
    recalc = function () {
      var clientWidth = docEl.clientWidth;
      if (!clientWidth) return;
      docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
      /*
       * 100 -> html,body { font-size:100px; }
       * 750 -> 此處以 iPhone6 兩倍設計稿 寬度750px 布局頁面
       * 根據具體情況改變這兩個數值
       */
    };
  if (!doc.addEventListener) return;
  // 窗口大小發生變化,初始化
  win.addEventListener(resizeEvt, recalc, false);
  doc.addEventListener('DOMContentLoaded', recalc, false);
  //防止在html未加載完畢時執行,保證獲取正確的頁寬
  setTimeout(function(){
    px2rem(doc, win);
  }, 200);
})(document, window);

countUp.js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
(function(root, factory) {
 if (typeof define === 'function' && define.amd) {
  define(factory);
 } else if (typeof exports === 'object') {
  module.exports = factory(require, exports, module);
 } else {
  root.CountUp = factory();
 }
}(this, function(require, exports, module) {
 
/*
 
    countUp.js
    by @inorganik
 
*/
 
// target = id of html element or var of previously selected html element where counting occurs
// startVal = the value you want to begin at
// endVal = the value you want to arrive at
// decimals = number of decimal places, default 0
// duration = duration of animation in seconds, default 2
// options = optional object of options (see below)
 
var CountUp = function(target, startVal, endVal, decimals, duration, options) {
 
    var self = this;
    self.version = function () { return '1.9.3'; };
    
    // default options
    self.options = {
        useEasing: true, // toggle easing
        useGrouping: true, // 1,000,000 vs 1000000
        separator: ',', // character to use as a separator
        decimal: '.', // character to use as a decimal
        easingFn: easeOutExpo, // optional custom easing function, default is Robert Penner's easeOutExpo
        formattingFn: formatNumber, // optional custom formatting function, default is formatNumber above
        prefix: '', // optional text before the result
        suffix: '', // optional text after the result
        numerals: [] // optionally pass an array of custom numerals for 0-9
    };
 
    // extend default options with passed options object
    if (options && typeof options === 'object') {
        for (var key in self.options) {
            if (options.hasOwnProperty(key) && options[key] !== null) {
                self.options[key] = options[key];
            }
        }
    }
 
    if (self.options.separator === '') {
        self.options.useGrouping = false;
    }
    else {
        // ensure the separator is a string (formatNumber assumes this)
        self.options.separator = '' + self.options.separator;
    }
 
    // make sure requestAnimationFrame and cancelAnimationFrame are defined
    // polyfill for browsers without native support
    // by Opera engineer Erik Möller
    var lastTime = 0;
    var vendors = ['webkit', 'moz', 'ms', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }
    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };
    }
    if (!window.cancelAnimationFrame) {
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
    }
 
    function formatNumber(num) {
        var neg = (num < 0),
        x, x1, x2, x3, i, len;
        num = Math.abs(num).toFixed(self.decimals);
        num += '';
        x = num.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? self.options.decimal + x[1] : '';
        if (self.options.useGrouping) {
            x3 = '';
            for (i = 0, len = x1.length; i < len; ++i) {
                if (i !== 0 && ((i % 3) === 0)) {
                    x3 = self.options.separator + x3;
                }
                x3 = x1[len - i - 1] + x3;
            }
            x1 = x3;
        }
        // optional numeral substitution
        if (self.options.numerals.length) {
            x1 = x1.replace(/[0-9]/g, function(w) {
                return self.options.numerals[+w];
            })
            x2 = x2.replace(/[0-9]/g, function(w) {
                return self.options.numerals[+w];
            })
        }
        return (neg ? '-' : '') + self.options.prefix + x1 + x2 + self.options.suffix;
    }
    // Robert Penner's easeOutExpo
    function easeOutExpo(t, b, c, d) {
        return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
    }
    function ensureNumber(n) {
        return (typeof n === 'number' && !isNaN(n));
    }
 
    self.initialize = function() {
        if (self.initialized) return true;
        
        self.error = '';
        self.d = (typeof target === 'string') ? document.getElementById(target) : target;
        if (!self.d) {
            self.error = '[CountUp] target is null or undefined'
            return false;
        }
        self.startVal = Number(startVal);
        self.endVal = Number(endVal);
        // error checks
        if (ensureNumber(self.startVal) && ensureNumber(self.endVal)) {
            self.decimals = Math.max(0, decimals || 0);
            self.dec = Math.pow(10, self.decimals);
            self.duration = Number(duration) * 1000 || 2000;
            self.countDown = (self.startVal > self.endVal);
            self.frameVal = self.startVal;
            self.initialized = true;
            return true;
        }
        else {
            self.error = '[CountUp] startVal ('+startVal+') or endVal ('+endVal+') is not a number';
            return false;
        }
    };
 
    // Print value to target
    self.printValue = function(value) {
        var result = self.options.formattingFn(value);
 
        if (self.d.tagName === 'INPUT') {
            this.d.value = result;
        }
        else if (self.d.tagName === 'text' || self.d.tagName === 'tspan') {
            this.d.textContent = result;
        }
        else {
            this.d.innerHTML = result;
        }
    };
 
    self.count = function(timestamp) {
 
        if (!self.startTime) { self.startTime = timestamp; }
 
        self.timestamp = timestamp;
        var progress = timestamp - self.startTime;
        self.remaining = self.duration - progress;
 
        // to ease or not to ease
        if (self.options.useEasing) {
            if (self.countDown) {
                self.frameVal = self.startVal - self.options.easingFn(progress, 0, self.startVal - self.endVal, self.duration);
            } else {
                self.frameVal = self.options.easingFn(progress, self.startVal, self.endVal - self.startVal, self.duration);
            }
        } else {
            if (self.countDown) {
                self.frameVal = self.startVal - ((self.startVal - self.endVal) * (progress / self.duration));
            } else {
                self.frameVal = self.startVal + (self.endVal - self.startVal) * (progress / self.duration);
            }
        }
 
        // don't go past endVal since progress can exceed duration in the last frame
        if (self.countDown) {
            self.frameVal = (self.frameVal < self.endVal) ? self.endVal : self.frameVal;
        } else {
            self.frameVal = (self.frameVal > self.endVal) ? self.endVal : self.frameVal;
        }
 
        // decimal
        self.frameVal = Math.round(self.frameVal*self.dec)/self.dec;
 
        // format and print value
        self.printValue(self.frameVal);
 
        // whether to continue
        if (progress < self.duration) {
            self.rAF = requestAnimationFrame(self.count);
        } else {
            if (self.callback) self.callback();
        }
    };
    // start your animation
    self.start = function(callback) {
        if (!self.initialize()) return;
        self.callback = callback;
        self.rAF = requestAnimationFrame(self.count);
    };
    // toggles pause/resume animation
    self.pauseResume = function() {
        if (!self.paused) {
            self.paused = true;
            cancelAnimationFrame(self.rAF);
        } else {
            self.paused = false;
            delete self.startTime;
            self.duration = self.remaining;
            self.startVal = self.frameVal;
            requestAnimationFrame(self.count);
        }
    };
    // reset to startVal so animation can be run again
    self.reset = function() {
        self.paused = false;
        delete self.startTime;
        self.initialized = false;
        if (self.initialize()) {
            cancelAnimationFrame(self.rAF);
            self.printValue(self.startVal);
        }
    };
    // pass a new endVal and start animation
    self.update = function (newEndVal) {
        if (!self.initialize()) return;
        newEndVal = Number(newEndVal);
        if (!ensureNumber(newEndVal)) {
            self.error = '[CountUp] update() - new endVal is not a number: '+newEndVal;
            return;
        }
        self.error = '';
        if (newEndVal === self.frameVal) return;
        cancelAnimationFrame(self.rAF);
        self.paused = false;
        delete self.startTime;
        self.startVal = self.frameVal;
        self.endVal = newEndVal;
        self.countDown = (self.startVal > self.endVal);
        self.rAF = requestAnimationFrame(self.count);
    };
 
    // format startVal on initialization
    if (self.initialize()) self.printValue(self.startVal);
};
 
return CountUp;
 
}));

JavaScript實現消消樂的源代碼

index.css

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
a,body,button,dd,div,dl,dt,form,h1,h2,h3,h4,h5,h6,input,label,li,ol,p,span,table,td,textarea,th,tr,ul
{   -webkit-box-sizing:border-box;
    -moz-box-sizing:border-box;box-sizing:border-box;
    margin:0;padding:0;
    border:0;-webkit-tap-highlight-color:transparent
}
body,html{
    width:100%;min-height:100%;background-color:#fff;
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none
}
body
{color:#333;
font-family:微軟雅黑
}
h1,h2,h3,h4,h5,h6
{
font-weight:400;
font-size:100%
}
a{
color:#555
}
a,a:hover{
text-decoration:none
}
img{
border:none
}
li,ol,ul{
list-style:none
}
input,textarea{
outline:0;
-webkit-appearance:none
}
::-webkit-input-placeholder{
color:#b0b0b0
}
:-moz-placeholder,::-moz-placeholder{
color:#b0b0b0
}
:-ms-input-placeholder{
color:#b0b0b0
}
[v-cloak]{
display:none
}
.lucky-star{
position:fixed;
top:0;left:0;width:100%;
height:100%;
background-image:url(../images/cover.jpg);background-size:cover;background-repeat:no-repeat;font-size:0;
-moz-background-size:cover;
-o-background-size:cover
}
.score-target
{
padding:0 .3rem;height:1.5rem;
-webkit-box-pack:justify;
-webkit-justify-content:space-between;
-moz-box-pack:justify;
-ms-flex-pack:justify;
justify-content:space-between
}
.score-current,.score-target{
display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;
display:flex;width:100%;
color:#fff;font-size:.24rem;
-webkit-box-align:center;
-webkit-align-items:center;
-moz-box-align:center;
-ms-flex-align:center;
align-items:center
}
.score-current{
position:absolute;top:.3rem;
-webkit-box-orient:vertical;
-webkit-box-direction:normal;
-webkit-flex-direction:column;
-moz-box-orient:vertical;
-moz-box-direction:normal;
-ms-flex-direction:column;
flex-direction:column;
-webkit-box-pack:center;
-webkit-justify-content:center;
-moz-box-pack:center;
-ms-flex-pack:center;
justify-content:center
}
.score-current span{
color:#fffc0f;
font-size:.48rem
}
.score-select{
width:100%;
color:#fff;
text-align:center;
font-size:.28rem;opacity:0;
-webkit-transition:opacity 1s;
-moz-transition:opacity 1s;
-o-transition:opacity 1s;
transition:opacity 1s
}
 
.star-list{
position:fixed;
bottom:0;left:0;
width:100%;
height:70%}
.star-list li{
position:absolute;
width:.75rem;
height:.75rem;
border:0;
-webkit-border-radius:.16rem;
-moz-border-radius:.16rem;
border-radius:.16rem;
background-size:cover;
-webkit-transition:left .3s,bottom .3s,-webkit-transform .3s;-moz-transition:transform .3s,left .3s,bottom .3s,-moz-transform .3s;-o-transition:left .3s,bottom .3s,-o-transform .3s;transition:left .3s,bottom .3s,-webkit-transform .3s;transition:transform .3s,left .3s,bottom .3s;transition:transform .3s,left .3s,bottom .3s,-webkit-transform .3s,-moz-transform .3s,-o-transform .3s;
-moz-background-size:cover;
-o-background-size:cover
}
.star-list li.scale{
border:2px solid #bfefff;
-webkit-animation:scale .3s linear infinite alternate;
-moz-animation:scale .3s linear infinite alternate;
-o-animation:scale .3s linear infinite alternate;animation:scale .3s linear infinite alternate}
.star-list li img{position:absolute;top:15%;left:15%;width:70%;height:70%
}@-webkit-keyframes scale{
0%{-webkit-transform:scale(1);transform:scale(1)
}
to{
-webkit-transform:scale(.95);
transform:scale(.95)
}
}
@-moz-keyframes scale{
0%{
-moz-transform:scale(1);
transform:scale(1)}
to{
-moz-transform:scale(.95);
transform:scale(.95)
}
}
@-o-keyframes scale{
0%{
-o-transform:scale(1);
transform:scale(1)
}
to{
-o-transform:scale(.95);transform:scale(.95)
}
}
@keyframes scale{
0%{
-webkit-transform:scale(1);
-moz-transform:scale(1);
-o-transform:scale(1);
transform:scale(1)
}
to
{
-webkit-transform:scale(.95);
-moz-transform:scale(.95);
-o-transform:scale(.95);transform:scale(.95)
}
}

.DS_Store

到此這篇關于JavaScript實現消消樂-源代碼的文章就介紹到這了,更多相關js實現消消樂內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!

原文鏈接:https://blog.csdn.net/qq_44757034/article/details/112129786

延伸 · 閱讀

精彩推薦
  • js教程JavaScript代碼實現簡單計算器

    JavaScript代碼實現簡單計算器

    這篇文章主要為大家詳細介紹了JavaScript代碼實現簡單計算器,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    小蟲蟲~4042021-12-21
  • js教程JavaScript 中的六種循環方法

    JavaScript 中的六種循環方法

    這篇文章主要介紹了JavaScript 中的六種循環方法,幫助大家更好的理解和使用JavaScript,感興趣的朋友可以了解下...

    Saku8462021-12-27
  • js教程微信小程序自定義支持圖片的彈窗

    微信小程序自定義支持圖片的彈窗

    這篇文章主要為大家詳細介紹了微信小程序自定義支持圖片的彈窗,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    歲末Zzz8172021-12-15
  • js教程在HTML中使用JavaScript的兩種方法

    在HTML中使用JavaScript的兩種方法

    這篇文章主要介紹了在HTML中使用JavaScript的兩種方法,幫助大家更好的理解和制作網頁,感興趣的朋友可以了解下...

    itbsl9222021-12-18
  • js教程一篇文章教會你使用 JavaScript 創建對象

    一篇文章教會你使用 JavaScript 創建對象

    本文基于JavaScrip基礎,介紹如何去創建一個對象,通過從最基礎的對象屬性,對象方法,使用new Object()創建構造方法,最后介紹了對象的可變性,比較對象...

    前端進階學習交流8082021-12-28
  • js教程微信小程序彈窗禁止頁面滾動的實現代碼

    微信小程序彈窗禁止頁面滾動的實現代碼

    這篇文章主要介紹了微信小程序彈窗禁止頁面滾動的實現代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需...

    任我行RQ5452021-12-23
  • js教程JavaScript Html實現移動端紅包雨功能頁面

    JavaScript Html實現移動端紅包雨功能頁面

    這篇文章主要為大家詳細介紹了JavaScript Html實現移動端紅包雨功能頁面,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考...

    Jeslie-He4672021-12-29
  • js教程js動態生成表格(節點操作)

    js動態生成表格(節點操作)

    這篇文章主要為大家詳細介紹了js動態生成表格,進行節點操作,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    劉劉劉code3342021-12-30
主站蜘蛛池模板: 日韩精品亚洲一级在线观看 | 韩国三级在线观看 完整版 韩国三级视频网站 | 日本精品人妖shemale人妖 | 男女发生性关系视频 | 日本乱人伦中文在线播放 | 午夜桃色剧场 | 日本护士厕所xxx | 四虎e234hcom | 五月色综合婷婷综合俺来也 | 国产成人精品第一区二区 | 99r在线播放 | 桃乃木香奈ipx在线播放 | b站免费网站入口 | 9色视频在线观看 | 美女班主任让我爽了一夜视频 | 好深快点再快点好爽视频 | 好涨好爽乱岳 | 日本老妇成熟 | 日本在线视频播放 | 欧美日韩国产中文字幕 | 欧美日韩看看2015永久免费 | 欧美一级欧美三级在线 | 99超级碰碰成人香蕉网 | 97爱干 | katsuniav在线播放 | 日本在线看| 韩国理论片最新第一页 | oneday高清在线观看 | 国产一区二区精品 | 久久伊人在 | 天美传媒果冻传媒星空传媒 | 亚洲国产精品无圣光一区二区 | 亚洲国产99在线精品一区二区 | 非洲黑人xxxxxbbbbb| 亚洲国产精品免费在线观看 | 性欧美13处丶14处 | 亚洲狠狠网站色噜噜 | 国产一级毛片国语版 | 国产精品啪啪 | 亚洲天堂2016| bban女同系列022在线观看 |