0
所以我正在做一個小遊戲,你必須按Ctrl來阻止div隨機跳躍。 但是我不能得到它的工作... jumpRandom函數工作正常,直到我把randomJump(){return false;};
內if (event.ctrlKey) {}
。我該怎麼做才能使它工作?按ctrl時停止功能jQuery
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
});
}
});
酷,它的工作!如果釋放ctrl,我怎麼讓'jumpRandom'再次工作? –
假設你取消註釋$(「#目標」)。 :)我把它留下了評論,因爲我不知道你是否希望它是永久的。這裏有一個演示它的小提琴:http://jsfiddle.net/QYsDN/ – pete
哦,顯然!^___ ^。謝謝! –