0

所以我正在制作一个小游戏,你必须按下Ctrl才能阻止 div 随机跳跃。但是我无法让它工作...... jumpRandom 函数工作正常,直到我randomJump(){return false;};if (event.ctrlKey) {}. 我应该怎么做才能让它工作?

js:

    $(document).ready(function() {

function randomFromTo(from, to){
            return Math.floor(Math.random() * (to - from + 1) + from);
}
$( "#goal" ).bind('mouseenter keypress', function(event) {
    if (event.ctrlKey) {
            randomJump(){return false;};
        }
});
$('#goal').mouseenter(randomJump);

function randomJump(){
            /* get Window position and size
             * -- access method : cPos.top and cPos.left*/
            var cPos = $('#pageWrap').offset();
            var cHeight = $(window).height() - $('header').height() - $('footer').height();
            var cWidth = $(window).width(); 

            // get box padding (assume all padding have same value)
            var pad = parseInt($('#goal').css('padding-top').replace('px', ''));

            // get movable box size
            var bHeight = $('#goal').height();
            var bWidth = $('#goal').width();

            // set maximum position
            maxY = cPos.top + cHeight - bHeight - pad;
            maxX = cPos.left + cWidth - bWidth - pad;

            // set minimum position
            minY = cPos.top + pad;
            minX = cPos.left + pad;

            // set new position         
            newY = randomFromTo(minY, maxY);
            newX = randomFromTo(minX, maxX);


            $('#goal').fadeOut(50, function(){

                $('#goal').fadeIn(700);
            });
            $('#goal').animate({
                    left: newX,
                    top: newY,
                    duration: 500
                });
        }
});
4

1 回答 1

2

尝试这个:

$("#goal").bind('mouseenter keypress', function (e) {
    randomJump(e);
});

function randomJump(e) {
    if (!e.ctrlKey) {
        //do normal stuff
    } else {
        //depending on how permanent you need this to be...
        //$("#goal").unbind('mouseenter keypress');
    }
    return !e.ctrlKey;
}
于 2012-10-31T09:56:34.250 回答