到达容器边框时停止移动图像

我有这个小提琴: http : //jsfiddle.net/ps4t9/4/

$(window).keydown(function (e) { if (e.which == 38) { player.animate({ top: '-=20px' }); shuriken.animate({ top: '-=20px' }); } // up if (e.which == 40) { player.animate({ top: '+=20px' }); shuriken.animate({ top: '+=20px' }); } // down if (e.which == 32) { shuriken.animate({ left: '+=280px' });} // space bar hit }); 

如何防止玩家移出集装箱边界?

您可以使用if语句

 if (e.which == 32){ if(shuriken.css('left') != '249px'){ shuriken.animate({ 'left' : '+=280px' }); } } 

小提琴: http : //jsfiddle.net/Hive7/ps4t9/5/

试试这个: http : //jsfiddle.net/ps4t9/11/

 $(document).ready(function () { var player = $("#Player"), shuriken = $("#Shuriken"), container = $("#Container"), w = container.width() - shuriken.width(); $(window).keydown(function (e) { if (e.which == 38) { if (parseInt(player.css('top')) > 10) { player.animate({ top: '-=20px' }); shuriken.animate({ top: '-=20px' }); } } // up if (e.which == 40) { if (parseInt(player.css('top')) < 270) { player.animate({ top: '+=20px' }); shuriken.animate({ top: '+=20px' }); } } // down if (e.which == 32) { if (shuriken.css('left') != '249px') { shuriken.animate({ 'left' : '+=280px' }); } } }); }); 

按住键并移动太快时会断开。 您可能还需要稍微调整一下这些值。

演示http://jsfiddle.net/u6vXK/1/

你想要的条件是什么

  var wallT = 0,//top wallB =269,//bottpm wallL = 0,//left wallR =269;//right function checkBoundUpDw(pos) { if(pos > wallT && pos < wallB){ return true; } return false; } function checkBoundleftRight(pos) { if(pos > wallL && pos  

如果你按住它不会工作,按键一个按键,表示按下并等待动画完成并再次按下,你必须添加isanimating条件和其他优势提示。

这是你的答案的链接

http://jsfiddle.net/bDMnX/7/

  var pane = $('#pane'), box = $('#box'), w = pane.width() - box.width(), d = {}, x = 3; function newv(v,a,b) { var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0); return n < 0 ? 0 : n > w ? w : n; } $(window).keydown(function(e) { d[e.which] = true; }); $(window).keyup(function(e) { d[e.which] = false; }); setInterval(function() { box.css({ left: function(i,v) { return newv(v, 37, 39); }, top: function(i,v) { return newv(v, 38, 40); } }); }, 20); 

谢谢大家的帮助,但经过深刻的冥想和搜索,我设法让它在这里工作是最后的jsfiddle: http : //jsfiddle.net/ps4t9/15/谢谢

  function newv(v, a, b) { var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0); return n < 0 ? 0 : n > w ? w : n; } $(window).keydown(function (e) { d[e.which] = true; if (e.which == 32) { if (!shurikenHitBorder) { shuriken.animate({ left: '+=280px' }, 'fast'); shuriken.fadeIn(100); } shurikenHitBorder = true; } }); $(window).keyup(function (e) { d[e.which] = false; }); setInterval(function () { box.css({top: function (i, v) { return newv(v, 38, 40); }}); }, 20); 

我已经编辑了你的JSFiddle进行了必要的修改。 这对你有帮助吗? 问我是否需要更多解释……

我已添加这些来帮助您计算最佳边界…

 posDelta = 20, // amount of change in position playerOffset = player.height() * 0.5, playerPos = player.position().top, maxTop = posDelta, maxBottom = container.height() - (posDelta + playerOffset);