jQuery反应测试延迟问题

时间:2013-10-03 02:25:17

标签: javascript jquery html css jsfiddle

我在制作反应测试时遇到了一些问题:

  • 嗯,首先我想在玩家点击div后随机暂停(2-5秒)。

  • 其次,我希望div总共出现5次,所以玩家有5次尝试。

对于第一个问题,我尝试使用setTimeout函数。我试图通过使用'for'循环来限制div出现的次数来解决第二个问题。

For example:

    for(var i = 1; i < 5; i++) {
        $div.css({
            left: Math.floor(Math.random() * widthMax),
            top: Math.floor(Math.random() * heightMax)
        });
    }

但是,我无法解决其中任何一个问题。

你可以在这里试试: http://jsfiddle.net/tghca/7/

任何帮助将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:1)

这样的东西
$('div').hide();

$('.start').click(function () {
    $(this).hide();
    $('.hint').hide();
    $('div').show();
    makeDiv();
});

var counter = 0;

function testClick() {
    var docHeight = $(document).height(),
        docWidth = $(document).width(),
        $div = $('#test'),
        divWidth = $div.width(),
        divHeight = $div.height(),
        heightMax = docHeight - divHeight,
        widthMax = docWidth - divWidth;

    $div.hide();
    setTimeout(function () {
        $div.css({
            left: Math.floor(Math.random() * widthMax),
            top: Math.floor(Math.random() * heightMax)
        }).show();
        counter++;
        if (counter < 5) {
            makeDiv();
        }
    }, Math.floor(Math.random() * 3000) + 2000)
}

function makeDiv() {
    $('#test').one('click', testClick);
}

演示:Fiddle

相关问题