尾牙抽獎老虎機

by lyhcode

HTML

<ul class="slot-machine">
    <li>0</li>
    <li>0</li>
    <li>0</li>
    <li>0</li>
    <li>0</li>
    <li>0</li>
</ul>
<div style="clear:both">
    <button id="start">Start</button>
    <button id="stop1">Stop 1</button>
    <button id="stop2">Stop 2</button>
</div>

CSS

body {
    background: #1B325F;
}
.slot-machine li.running-0 {
    background-position: 0 0;
}
.slot-machine li.running-1 {
    background-position: 0 50px;
}
.slot-machine li.running-2 {
    background-position: 0 100px;
}
.slot-machine li.running-3 {
    background-position: 0 150px;
}
.slot-machine li.running-4 {
    background-position: 0 200px;
}
.slot-machine li {
    background: url(http://dl.dropbox.com/u/21651474/test/slot-background.png) gray;
    color: #E9F2F9;
    width: 150px;
    height: 250px;
    float: left;
    font-size: 180px;
    font-family: Georgia;
    text-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
    display: table-cell;
    text-align: center;
    margin: 10px;
}
.slot-machine li.result {
    font-size: 200px;
}
.slot-machine li.run {
    color: transparent;
    text-shadow: #fff 0 0 20px;
}

JavaScript

var stop1 = false;
var stop2 = false;

var change = function(obj, i) {
    $(obj)
        .removeClass('running-0')
        .removeClass('running-1')
        .removeClass('running-2')
        .removeClass('running-3')
        .removeClass('running-4');
    if (i > 0) {
        $(obj).addClass('running-' + i);
    }
};

$('#start').click(function() {
    stop1 = stop2 = false;
    
    $('.slot-machine li').addClass('run');
    $('.slot-machine li').removeClass('result');
    
    var t = 0;
    
    var run = function() {
        var c = 0;
        $('.slot-machine li').each(function() {
            if (c < 3) {
                if (!stop1) {
                    $(this).text(Math.floor(Math.random()*10));
                    change(this, t % 5);
                }
            }
            else {
                if (!stop2) {
                    $(this).text(Math.floor(Math.random()*10));
                    change(this, t % 5);
                }
            }
            
            c++;
        });
        
        t++;
        
        if (!stop1 || !stop2) {
            window.setTimeout(run, 50);
        }
        else {
            //$('.slot-machine li').removeClass('run');
        }
    };
    window.setTimeout(run, 50);
});

$('#stop1').click(function() {
    stop1 = true;
    var c = 0;
    $('.slot-machine li').each(function() {
        if (c < 3) {
            $(this).removeClass('run');
            $(this).addClass('result');
            change(this, -1);
        }
        
        c++;
    });
});

$('#stop2').click(function() {
    stop2 = true;
    var c = 0;
    $('.slot-machine li').each(function() {
        if (c >= 3) {
            $(this).removeClass('run');
            $(this).addClass('result');
            change(this, -1);
        }
        
        c++;
    });
});