繁体   English   中英

jQuery-修复动画

[英]jQuery - Fixing the animation

我正在创建一个新的“打地鼠”风格的游戏,孩子们必须根据问题打正确的数字。

我将数字从机顶位置移动到另一个具有随机宽度的位置,以便它们看起来像气泡一样漂浮。

我唯一遇到的问题是,有时数字毛刺和数字宽度突然改变,使其看起来似乎从容器的一侧跳到另一侧。

我能想到的唯一解释是宽度必须在我试图寻找的某个地方重置。

我是盲人还是其他人,有人可以帮助我找到问题的根源。

这是映射数字的代码...

function randomFromTo(from, to) {
    return Math.floor(Math.random() * (to - from + 1) + from);
}

function scramble() {
    var children = $('#container').children();
    var randomId = randomFromTo(1, children.length);
    moveRandom("char" + randomId);
}

function moveRandom(id) {
    var cPos = $('#container').offset();
    var cHeight = $('#container').height();
    var cWidth = $('#container').width();
    var bWidth = $('#' + id).width();

    var bHeight = $('#' + id).css(
        'top', '400px'
    ).fadeIn(1000).animate({
    '   top': '-100px'
    }, 10000).fadeOut(1000);

    maxWidth = cPos.left + cWidth - bWidth;
    minWidth = cPos.left;
    newWidth = randomFromTo(minWidth, maxWidth);

    $('#' + id).css({
        left: newWidth
    }).fadeIn(1000, function () {
        setTimeout(function () {
            $('#' + id).fadeOut(1000);
            window.cont++;
        }, 1000);
    });

这也是一个有效的小提琴,因此您可以看到我正在谈论的问题: http : //jsfiddle.net/pUwKb/26/

问题是您要为已经设置动画的ID重新输入moveRandom函数。 新的宽度计算会导致在已经进行动画处理的运动中重新分配作品时,它似乎会跳跃。 解决此问题的一种方法是拒绝已设置动画的作品的新作品运动。 我修改了您的jsFiddle并使用以下代码对其进行了修复:

// Keep track of the pieces actually moving
var currentMoving = [];

function moveRandom(id) {
    // If this one's already animating, skip it
    if ($.inArray(id, currentMoving) !== -1) {
        return;
    }

    // Mark this one as animating
    currentMoving.push(id);

    var cPos = $('#container').offset();
    var cHeight = $('#container').height();
    var cWidth = $('#container').width();
    var bWidth = $('#' + id).width();

    var bHeight = $('#' + id).css('top', '400px').fadeIn(1000).animate({
        'top': '-100px'
    }, 10000).fadeOut(1000);

    maxWidth = cPos.left + cWidth - bWidth;
    minWidth = cPos.left;
    newWidth = randomFromTo(minWidth, maxWidth);

    $('#' + id).css({
        left: newWidth
    }).fadeIn(1000, function () {
        setTimeout(function () {
            $('#' + id).fadeOut(1000);

            // Mark this as no longer animating                
            var ix = $.inArray(id, currentMoving);
            if (ix !== -1) {
                currentMoving.splice(ix, 1);
            }

            window.cont++;
        }, 1000);
    });
}

在这里分叉jsFiddle。

编辑 :OP希望一次显示更多的div,而又不加快动画的速度。 为此,我又添加了20个字符div(每个字符都与前10个数字重复),稍微修改了保护代码,更改了CSS以按类指定字符的图像,然后将一个动画限制为20个给定时间。 我还围绕已经拒绝制作动画的作品循环播放,以选择另一个。 我做了其他一些小的改进。 在此更新了JSFiddle。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM