创作之前,你得先会模仿
在写这篇文章之前,我对这主题要怎么实现其实也是 have no idea..
好在生在这个网路资讯发达的年代, 善用google, 可以解决你人生很多问题
所以我们这周就来看一下其他大大的範例
小玛莉模拟 by MrJohnson
小巧且完整 ~
好的,那我们来看一下code, 那么从哪里开始看呢?
先大致上浏览一下程式, 我们可以看到
var no = 0;var stopPlay = 0;var runTimes = 0;var sec = 50;init();function play() { ...}function init() { ...}$("button").click(function() { ...});$(".popup-close").click(function() { ...});
hmm... 四个变数no, stopPlay, runTimes, sec, 看不太懂...
一切操作的起始就在"立即抽奖"button的点击事件开始, 所以我们首先看到buuton onClick function的部分
$("button").click(function() { if (runTimes > 0) return; stopPlay = Math.floor(Math.random() * (20 - 0) + 20); $(this).attr("disabled", true); play();});
这边可以看到作者将 stopPlay 指定了一个乱数, 接着执行 play函式
接着我们看一下play里面在干嘛
function play() { no++; runTimes++; if (no >= 11) { no = 1; } if (runTimes > stopPlay) { $(".light").css("animation-duration", "2s"); var href = $("#letmeopen"); $(href).fadeIn(250); $("#winPrizes").text($(".active").text()); $(href).children$("popup-box").removeClass("transform-out").addClass("transform-in"); e.preventDefault(); } else if (runTimes + 10 > stopPlay) { $(".no" + no) .addClass("active") .siblings() .removeClass("active"); setTimeout(play, (sec = sec * 1.4)); } else { $(".no" + no) .addClass("active") .siblings() .removeClass("active"); setTimeout(play, sec); $(".light").css("animation-duration", ".3s"); }}
我们先忽略程式中里面关于DOM的操作, 所以整体看起来是这样的
function play() { no++; runTimes++; if (no >= 11) { no = 1; } if (runTimes > stopPlay) { // dosomething } else if (runTimes + 10 > stopPlay) { // dosomething setTimeout(play, (sec = sec * 1.4)); } else { // dosomething setTimeout(play, sec); }}
这样看起来就清楚多了, 在这里面由于变数stopPlay已经被指定了一个乱数, 在runTime大于stopPlay之前, 它会重複执行play函式本身, 间隔为sec当runTime 与 stopPlay 间隔10以内时, 间隔每次*1.4那no是干嘛用的呢, 我们看一下else里面其他部分
$(".no" + no) .addClass("active") .siblings() .removeClass("active");
这边做了一些DOM的操作, 再参照HTML的部分, 我们可以知道no 就是对应到HTML的奖项DOM, 至此我们可以归纳出整段程式的运作逻辑
先骰个骰子 (骰之前重置一下参数)stopPlay:这次要前进几步runTime:现在走到第几步no:当前的灯号是停在哪一格上面 (如果no>=11也就是超过总格数了, 那就重置为1)如果还没走到指定的步数就在走一步 (如果再十步内就要走到了,那就愈走愈慢)配合目前走道的格数no去做DOM的效果操作, 如果走完了就popup出中奖详细资讯到这边我们就理解了一个简易的小玛莉游戏的程式逻辑及操作方式, 咱下周见