且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用箭头键移动元素

更新时间:2023-08-26 14:47:52

我不确定您是否仍然需要解决方案,但是您可以检查一下: http://jsfiddle.net/ft2PD/41/

i'm not sure if you still need a solution or not but you can check this one out: http://jsfiddle.net/ft2PD/41/

这是html

<div id='div1'>
    <input type='text' value='hello' />
</div>

<div id='div2'>
    <label> World</label>
</div>

这是JavaScript:

and here is the javascript:

$(document).ready(function(){
    $('#div1,#div2').click(function(){
        $('div.selected').removeClass('selected');
        $(this).addClass('selected');

    })}).keyup(function(e){
        var div = $('div.selected');
        console.log(div);
        console.log(e.which);            
        switch (e.which) {
    case 37:
        $(div).stop().animate({
            left: '-=10'
        }); //left arrow key
        break;
    case 38:
        $(div).stop().animate({
            top: '-=10'
        }); //up arrow key
        break;
    case 39:
        $(div).stop().animate({
            left: '+=10'
        }); //right arrow key
        break;
    case 40:
        $(div).stop().animate({
            top: '+=10'
        }); //bottom arrow key
        break;
    }
    });​

最后放置CSS

#div1
{
    position: absolute;
    width:100px;
    height:100px;
    margin:15px;
    padding:15px;
    border: thin solid #D2D2D2;
}
#div2
{
    position: absolute;
    width:50%;
    margin:15px;
    padding:15px;
    border: thin solid #D2D2D2;
}
.selected
{
    border: 1px dashed #cccccc !important;
}​