首页 > 解决方案 > 如何使用 JQuery 防止图像跳出窗口

问题描述

我正在尝试使用向上、向下、向左和向右的箭头键在屏幕上移动一个简单的图像。它工作得很好,只是图像一直从窗口出去,我看不到。我想要做的是将图像保持在窗口范围内而不是超出它。

这是我的代码:

let height = $(window).height();
let width = $(window).width();

$(document).keydown(function(key) {
  switch (parseInt(key.which, 10)) {
    // Left arrow key pressed
    case 37:
      if ($('img').position().left > 0) {
        $('img').animate({
          left: "-=20px"
        }, 'fast');
      }
      break;
      // Up Arrow Pressed
    case 38:
      if ($('img').position().top > 0) {
        $('img').animate({
          top: '-=20px'
        }, 'fast');
      }
      break;
      // Right Arrow Pressed
    case 39:
      if ($('img').position().left < width) {
        $('img').animate({
          left: '+=20px'
        }, 'fast');
      }
      break;
      // Down Arrow Pressed
    case 40:
      if ($('img').position().top < height) {
        $('img').animate({
          top: '+=20px'
        }, 'fast');
      }
      break;
  }
});
body {
  width: 100%;
  height: 100%;
  background: blue;
  overflow: hidden;
  /*This is the solution*/
}

img {
  position: relative;
  left: 0;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<img src="http://pngimg.com/uploads/mario/mario_PNG129.png" />

标签: javascriptjqueryhtmlcss

解决方案


似乎您只需要再计算一次。以向右移动为例,如果图像当前的右侧位置距离屏幕边缘 5px,会发生什么情况?然后($('img').position().right > width)将计算为真,它会移动 20 像素,使其离开屏幕 15 像素。

因此,您只需要考虑这种潜力。

if($('img').position().right > 0){
    distance = ( ($('img').position().left - width) < 20 ) ? ($('img').position().left - width) : 20;
    $('img').animate({left: "+="+distance+"px"}, 'fast');
}

在这里我们说,如果图像的当前位置距离右边缘小于 20px,则仅将其移动该差异,否则,将其移动 20px。

需要将类似的逻辑应用于底部,以确保图像的移动不会超过屏幕的高度。

我建议在底部和左侧也应用相同的逻辑。它当前没有移出屏幕的原因是因为您从 0,0 开始,一次移动 20px。它总是会回到 0,0。但是,如果您必须将其向右移动 12px 以保持在边界内,那么当您将其移回时,您可能会在左侧遇到同样的问题。希望这是有道理的。


推荐阅读