2017-01-29 57 views
-1

我目前有一個對象,我可以使用鍵盤上的箭頭鍵移動,但是,該對象移出屏幕。我怎樣才能讓對象留在屏幕上?如何防止移動字符離開屏幕

$(document).ready(function(){ 

    $(document).keydown(function(key) { 
     switch(parseInt(key.which,10)) { 
      case 37: 
       $('img').animate({left: "-=30px"}, 'fast'); 
       break; 
      case 38: 
       $('img').animate({top: '-=30px'},'fast'); 
       break; 
      case 39: 
       $('img').animate({left: '+=30px'},'fast'); 
       break; 
      case 40: 
       $('img').animate({top: '+=30px'},'fast'); 
       break; 
     } 
    }); 
}); 
+0

你的代碼在哪裏? –

+0

已添加代碼 – Pyro

回答

0

Fiddle

我已刪除了動畫,因爲動畫過程中,位置()。離開將會給E中的老值和left位置值僅動畫後更新。所以在這種情況下,即使代碼存在,圖片也可以移出窗口。如果你需要使用動畫,你應該考慮一些超時功能。

+0

非常感謝! – Pyro