how to move a div with arrow keys

后端 未结 4 777
我寻月下人不归
我寻月下人不归 2020-12-01 01:47

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 ab

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 02:31

    @Šime Vidas: Your first solution is simply marvelous. (i think the second one is redundant =)

    May i suggest to make two different functions for the vertical and the horizontal width? Because it’s highly unlikely that you have to move around a div inside a perfect square and i believe it would be nicer to have something like this:

    $(function () {
    var pane = $('#pane'),
    box = $('#box'),
    wh = pane.width() - box.width(),
    wv = pane.height() - box.height(),
    d = {},
    x = 5;
    
    function newh(v,a,b) {
        var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
        return n < 0 ? 0 : n > wh ? wh : n;
    }
    
    function newv(v,a,b) {
        var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
        return n < 0 ? 0 : n > wv ? wv : 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 newh(v, 37, 39); },
            top: function(i,v) { return newv(v, 38, 40); }
        });
    }, 20);
    });
    

    This would have been exactly what i was looking for.

    If you had a responsive design based on % values it would be recommendable to adjust your setInterval like this:

    setInterval(function() {
        box.css({
            left: function(i,v) { return newh(v, 37, 39); },
            top: function(i,v) { return newv(v, 38, 40); }
        });
        wh = pane.width() - box.width();
        wv = pane.height() - box.height();
    }, 20);
    

    if you do that it adjusts your panes height and width and the box still stops at its border.

    i made a fiddle of that here http://jsfiddle.net/infidel/JkQrR/1/

    Thanks a lot.

提交回复
热议问题