如何创建水平老虎机效果?

时间:2021-06-11 08:04:50

标签: javascript jquery random spinning

我有一个任务需要完成。

我需要一台水平老虎机,随机选择除 2 个项目之外的项目(因此,如果有 4 个项目,则旋转应仅在其中 2 个处停止),并且当旋转停止在项目处时,它应自动重定向到另一个页面。

这是代码:

$(document).ready(function () {

    // Clone the first element and append it to the end of the list
    var list = $('#slotmachine>ul:first');
    var firstItem = list.find('li:first');
    firstItem.clone().appendTo(list);

    function moveTo(val) {
        val = -val % 1200;
        if (val > 0) val -= 1200;
        $('#slotmachine').css({
            left: val
        });
    }

    function spin(count) {
        $('#slotmachine').stop().animate({
            left: -1200
        }, 2000, 'linear', function () {
            if (count == 0) {
                var slot = Math.floor(Math.random() * 4),
                    left = -slot * 200,
                    time =  2000 * slot / 4;
                console.log(count, slot, top, time)
                $(this).css({
                   left: 0
                }).animate({
                    left: left
                },time, 'easeOutQuad')
            } else {
                $(this).css({
                    left: 3
                })
                spin(count - 1)
            };
        });
    }
    $('#start').click(function () {
        $('#slotmachine').css({
            left: 0
        }) 
        spin(1)
    });

    $('#moveTo').click(function () {
        moveTo($('#pos').val());
    });
});
#viewbox {
   display:flex;
    width: 300px;
    height: 200px;
    border: solid 1px #000;
    position: relative;
}
#viewbox .wrapper {
    position: relative;
}
#viewbox ul {
  display:flex;
    list-style: none;
    margin: 0;
    padding: 0;
}
#viewbox li {
    display: block;
    width: 300px;
    height: 200px;
    text-align: center;
    font-size: 170px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="viewbox">
    <div class="wrapper" id="slotmachine">
        <ul>
            <li style="background:#f00">1</li>
            <li style="background:#ff0">2</li>
            <li style="background:#0f0">3</li>
            <li style="background:#0ff">4</li>
  
        </ul>
    </div>
</div>
<input type="button" value="start" id="start" />|
<input type="button" value="move To" id="moveTo" />
<input type="text" id="pos" value="0" size="5" />

现在不能正常工作...

我怎样才能做到这一点?

0 个答案:

没有答案