如何在外部div中限制移动div?

use*_*675 5 html javascript jquery key-events keydown

所以我用你的箭头键移动了一个div,但我怎么做它所以它不能超出"border div"?

$(document).ready(function(){
  $(document).keydown(function(e) {
      switch (e.which) {
      case 37: // Left
        $("#cube").css("left", $("#cube").offset().left - 101);
        break;
      case 38: // Up
        $("#cube").css("top", $("#cube").offset().top - 11);
        break;
      case 39: // Right
        $("#cube").css("left", $("#cube").offset().left - 97);
        break;
      case 40: // Down
        $("#cube").css("top", $("#cube").offset().top - 7);
        break;
      }
  });
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/SfKHN/

tay*_*10r 0

您添加简单的 if 语句来确保您没有越过边界。这是一个例子:

$(document).ready(function(){
    $(document).keydown(function(e) {
        switch (e.which) {

            case 38: // Up
                if( ( $("#cube").offset().top - 11 ) >= 0 )
                    $("#cube").css("top", $("#cube").offset().top - 11);
                break;

            case 40: // Down
                if( ( $( "#cube" ).offset( ).top - 7 ) < ( 400 - 50 ) )
                    $("#cube").css("top", $("#cube").offset().top - 7 );
                break;
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

您可以对左右箭头进行类似的更改