仅在另一个<div>内移动keydown()上的<div>

时间:2016-04-08 18:14:16

标签: jquery keydown

我试图在我的.game-box div中移动.red-ball而没有.red-ball离开div。我在寻求帮助,但无法弄清楚这是否应该在我的CSS或我的jQuery中修复。以下是我的HTML代码:

$(document).ready(function() {
  var ball = '<div class="red-ball"></div>';
  $('.game-box').append(ball);

  $(document).keydown(function(e) {
    var position = $('.red-ball').position();
    switch (e.keyCode) {
      case 37: //left
        $('.red-ball').css('left', position.left - 20 + 'px');
        break;
      case 38: //up
        $('.red-ball').css('top', position.top - 20 + 'px');
        break;
      case 39: //right
        $('.red-ball').css('left', position.left + 20 + 'px');
        break;
      case 40: //down
        $('.red-ball').css('top', position.top + 20 + 'px');
        break;
    }
  });
});
$gray:#ccccb3;
 $red:red;
 .game-box {
  position: relative;
  width: 100%;
  height: 500px;
  background-image: url('http://www.integrity-apps.com/wp-content/uploads/2014/09/BlueSpace.jpg');
  border: 1px solid black;
}
.red-ball {
  position: absolute;
  background-color: $red;
  width: 80px;
  height: 80px;
  border-radius: 50%;
}
<!DOCTYPE html>
<html>
<head>
  <title>The Ballin Game</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="sass/css/style.css">
  <script type="text/javascript" src="index.js"></script>
</head>

<body>
  <div class="container">
    <div class="page-header">
      <h1 class="text-center">Welcome to The Ballin Game</h1>
    </div>
  </div>

  <div class="container">
    <div class="game-box"></div>
  </div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

它应该在你的jQuery中...当球在边界时,你需要跳过运行switch(e.keyCode)

您可以使用getBoundingClientRect();来获取.game-box的边界矩形,然后使用if语句确保只有在球不在{的边缘时才运行按键{1}}。

有关.game-box方法的详情,请参阅https://developer.mozilla.org/en/docs/Web/API/Element/getBoundingClientRect

希望能帮助您开始解决方案!