按ctrl jQuery时停止功能

时间:2012-10-31 09:40:39

标签: javascript jquery mouseenter ctrl

所以我正在做一个小游戏,你必须按 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
                });
        }
});

1 个答案:

答案 0 :(得分: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;
}