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

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

问题描述

我想用jQuery的箭头键移动一个div。
对,左,下和向下。



发现我想要完成的一个演示这里



我想要在另一个div中移动一个div。



如何做到这一点?

解决方案

HTML:

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

CSS:

 code> #pane {
position:relative;
width:300px;高度:300像素;
border:2px solid red;
}

#box {
position:absolute;顶:140px;左:140px;
width:20px;高度:20像素;
background-color:black;
}

JavaScript:



<$

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

函数newv(v,a,b){
var n = parseInt(v,10) - (d [a]?x:0)+(d [b] :0);
返回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);

变量说明:

w - 该框可以拥有的最大左/顶值(保持在边界内)

x - 距离(以px为单位)该框在每个间隔中移动

d - 此对象存储有关按下什么键的信息。例如,当用户按住左箭头键时, d ['37'] true 。否则它是 false 。 BTW, 37 是LEFT ARROW键的键代码,此值存储在 e.which 属性中的事件对象。每个 keydown keyup 中更新 d 事件。



每隔20ms执行一次setInterval,更新box元素的左上角和顶层CSS属性。新值通过 newv 函数计算。



newv 函数将基于a)旧值 v 和b) d 对象。



表达式 n < 0? 0:n> w? w:n 确保新值在允许的范围内(这是 0到w )。如果n是< 0,将返回0。如果n为> w,则返回w。






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






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

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

函数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);
},
顶部:function(index,oldValue){
return calculateNewValue(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?

解决方案

HTML:

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

CSS:

#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;
}

JavaScript:

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);

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天全站免登陆