2011-03-25 21 views
2

我這裏有一個小提琴: http://jsfiddle.net/maniator/SZpkF/1/試圖移動框,按鍵和它不工作

綠盒應該與arrowkeys移動。有人可以解釋爲什麼它不會工作嗎?

JS:

var game = { 
    playArea: null, 
    player: null, 
    init: function() { 
     this.playArea = $('<div>', { 
      style: 'background-color: #AAF;' 
     }); 
     this.player = $('<span>'); 
     this.player.css({ 
      width: 20, 
      height: 20, 
      'background-color': '#AFA', 
      display: 'block', 
      position: 'absolute', 
      top: 0, 
      left: 0 
     }) 
     $(window).resize(game.resize); 
     $('body').append(this.playArea); 
     this.resize(); 
     this.playArea.append(this.player); 
     $(document).keydown(function(event) { 
      game.keydown(event) 
     }) 
     return this; 
    }, 
    resize: function() { 
     //console.log('resize', game); 
     game.playArea.css({ 
      width: $(window).width() - 50, 
      height: $(window).height() - 50, 
     }); 
     return this; 
    }, 
    keydown: function(event) { 
     var direction; 
     switch (event.keyCode) { 
     case 38: 
      direction = { 
       'top': '-= 15' 
      }; 
      break; 
     case 40: 
      direction = { 
       'top': '+= 15' 
      }; 
      break; 
     case 37: 
      direction = { 
       'left': '+= 15' 
      }; 
      break; 
     case 39: 
      direction = { 
       'left': '-= 15' 
      }; 
      break; 
     } 
     console.log(direction, event, game.player); 
     game.player.animate(direction, 'slow'); 
    } 
}; 

$(function() { 
    game.init(); 
}) 

回答

3

看起來不像jQuery的喜歡-=+=後的空間。我刪除了這些,但它的工作,雖然方向相反。

+1

另外,使用'event.which',它被標準化爲跨瀏覽器。 – 2011-03-25 05:21:18

+0

非常感謝!那工作:-)。虐待接受時,我可以:-D – Neal 2011-03-25 05:21:53

+0

哈哈ddnt注意到方向是倒退BC它沒有工作。現在我修復它^ _ ^ – Neal 2011-03-25 05:24:47