如何使用箭头键移动div [英] how to move a div with arrow keys

查看:27
本文介绍了如何使用箭头键移动div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 jQuery 用我的箭头键移动一个 div.如此向右、向左、向下和向上.

找到了我想要完成的演示 这里

我希望能够在另一个 div 中移动一个 div.

如何做到这一点?

解决方案

var pane = $('#pane'),box = $('#box'),w = pane.width() - box.width(),d = {},x = 3;函数 newv(v,a,b) {var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);返回 n <0 ?0 : n >?w : n;}$(window).keydown(function(e) { d[e.which] = true; });$(window).keyup(function(e) { d[e.which] = false; });设置间隔(函数(){box.css({左:function(i,v) { return newv(v, 37, 39);},顶部:函数(i,v){返回新v(v,38,40);}});}, 20);

#pane {位置:相对;宽度:300px;高度:300px;边框:2px纯红色;}#盒子 {位置:绝对;顶部:140px;左:140px;宽度:20px;高度:20px;背景颜色:黑色;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="窗格"><div id="box"></div>

变量解释:
w - 框可以具有的最大左/上值(保持在边界内)
x - 盒子在每个间隔内移动的距离(以像素为单位)
d - 此对象存储有关按下哪个键的信息.例如,当用户按住左箭头键时,d['37']true.否则它是 false.顺便说一句,37 是左箭头键的键码,该值存储在事件对象的 e.which 属性中.d 对象在每个 keydownkeyup 事件上更新.

每 20 毫秒执行一次的 setInterval,更新 box 元素的 left 和 top CSS 属性.新值通过 newv 函数计算.

newv 函数将根据 a) 旧值 v 和 b) d 对象计算新的左/上值.

表达式 n <0 ?0 : n >?w : n 确保新值在允许的范围内(0 到 w).如果 n <0,将返回零.如果 n 是 >w, w 会被返回.


现场演示:http://jsfiddle.net/simevidas/bDMnX/1299/


更新:此代码与上面的原始代码具有相同的功能.唯一的区别是我为变量和参数使用了更有意义的名称.如您所见,它看起来很糟糕 - 原始版本显然更好.:P

var pane = $('#pane'),box = $('#box'),maxValue = pane.width() - box.width(),按键按下 = {},距离PerIteration = 3;函数计算新值(旧值,keyCode1,keyCode2){var newValue = parseInt(oldValue, 10)- (keysPressed[keyCode1] ? distancePerIteration : 0)+ (keysPressed[keyCode2] ? distancePerIteration : 0);返回新值<0 ?0 : 新值 >最大值?最大值:新值;}$(window).keydown(function(event) { keysPressed[event.which] = true; });$(window).keyup(function(event) { keysPressed[event.which] = false; });设置间隔(函数(){box.css({左:函数(索引,旧值){返回计算新值(oldValue, 37, 39);},顶部:函数(索引,旧值){返回计算新值(oldValue, 38, 40);}});}, 20);

I would like to move a div with my arrow keys using jQuery. So right, left, down and up.

Found a demo of what I want to accomplish here

I would like to be able to move a div around in another div.

How can this be done?

解决方案

var pane = $('#pane'),
    box = $('#box'),
    w = pane.width() - box.width(),
    d = {},
    x = 3;

function newv(v,a,b) {
    var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
    return n < 0 ? 0 : n > w ? w : n;
}

$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });

setInterval(function() {
    box.css({
        left: function(i,v) { return newv(v, 37, 39); },
        top: function(i,v) { return newv(v, 38, 40); }
    });
}, 20);

#pane {
  position: relative;
  width: 300px;
  height: 300px;
  border: 2px solid red;
}

#box {
  position: absolute;
  top: 140px;
  left: 140px;
  width: 20px;
  height: 20px;
  background-color: black;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="pane">
  <div id="box"></div>
</div>

Variable explanations:
w - the maximal left/top value that the box can have (to stay within bounds)
x - the distance (in px) that the box moves in each interval
d - this object stores the information on what key is being pressed. For instance, while the user holds down the LEFT ARROW key, d['37'] is true. Otherwise it's false. BTW, 37 is the key-code for the LEFT ARROW key and this value is stored in the e.which property of the event object. The d object is being updated on each keydown and keyup event.

An setInterval which is executed every 20ms, updates the left and top CSS properties of the box element. The new values are calculated via the newv function.

The newv function will calculate the new left/top value based on a) the old value v and b) the d object.

The expression n < 0 ? 0 : n > w ? w : n ensures that the new value is in the permitted bounds (which are 0 to w). If n is < 0, zero will be returned. If n is > w, w will be returned.


Live demo: http://jsfiddle.net/simevidas/bDMnX/1299/


Update: This code has the same functionality as the original code above. The only difference is that I used more meaningful names for my variables and arguments. As you can see, it looks awful - the original version is clearly better. :P

var pane = $('#pane'),
    box = $('#box'),
    maxValue = pane.width() - box.width(),
    keysPressed = {},
    distancePerIteration = 3;

function calculateNewValue(oldValue, keyCode1, keyCode2) {
    var newValue = parseInt(oldValue, 10)
                   - (keysPressed[keyCode1] ? distancePerIteration : 0)
                   + (keysPressed[keyCode2] ? distancePerIteration : 0);
    return newValue < 0 ? 0 : newValue > maxValue ? maxValue : newValue;
}

$(window).keydown(function(event) { keysPressed[event.which] = true; });
$(window).keyup(function(event) { keysPressed[event.which] = false; });

setInterval(function() {
    box.css({
        left: function(index ,oldValue) {
            return calculateNewValue(oldValue, 37, 39);
        },
        top: function(index, oldValue) {
            return calculateNewValue(oldValue, 38, 40);
        }
    });
}, 20);

这篇关于如何使用箭头键移动div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆