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



我正试图在我的.game boxdiv中移动.red球,而不让.red球离开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>

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

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

请参阅https://developer.mozilla.org/en/docs/Web/API/Element/getBoundingClientRect有关CCD_ 6方法的更多信息。

希望这能让你开始寻找解决方案!

最新更新