javascript - 如何使用 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" />
解决方案
似乎您只需要再计算一次。以向右移动为例,如果图像当前的右侧位置距离屏幕边缘 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 以保持在边界内,那么当您将其移回时,您可能会在左侧遇到同样的问题。希望这是有道理的。
推荐阅读
- python - 无法创建 Tensorflow 会话:“内部:为 CUDA 设备序号 n 初始化 StreamExecutor 失败”
- java - 泛型接口方法参数的实际类型
- vue.js - 单击复选框后,V-model 未更新
- console - 为什么输出以 asci 码而不是整数打印?dart
- c# - 协方差不适用于代表
- go - 编码 SNMP 消息并从代理读取响应
- tsql - 如何在 Visual Studio 2017 中更改 Transact-SQL 代码的自动格式?
- javascript - 将一组 JSON 对象从 Google 表格传递到 HTML 服务
- php - 更新购物车 Laravel
- c# - 使用 SSIS 从 Sharepoint 中提取 JSON 并导入 Oracle