如何使用箭头键以百分比移动div

时间:2012-05-28 03:44:31

标签: javascript jquery html responsive-design

我从另一个问题here on stackoverflow得到了这个脚本,它完美无缺。该脚本更新了px中的元素,我特别喜欢通过举起+左箭头键来对角移动元素的方式。

我现在的问题是:是否可以更改脚本,以便以百分比形式设置和更新元素的值?

这样做的原因是我正在开发一个具有响应式设计的网站,我需要相对于窗口大小在页面上保留(和移动)元素。我试图解决这个问题,但到目前为止还没有成功。

这是脚本:

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); }, //Function should set values in %
        top: function(i,v) { return newv(v, 38, 40); }   //here for left and top
    });
}, 20);

COFFE SCRIPT

jQuery ->       
    pane = $('body')
    box = $('.myDiv')
    w = pane.width() - box.width()
    c = [37,38,39,40] # Set key values for arrow keys in an array
    d = []
    x = 4

    newv = (v,a,b) ->
        n = parseInt(v, 10) - (if d[a] then x else 0) + (if d[b] then x else 0)
        if n < 0 then 0 else if n > w then w else n

    $(window).keydown((e) ->
        d[e.which] = true
    )

    $(window).keyup((e) -> 
        d[e.which] = false
        if true not in d and e.which in c #Check that all arrow keys are released

        divID = $('.myDiv').attr('id')  # Grab values from the element
        top = $('.myDiv').css('top')
        left = $('.myDiv').css('left')

        setTimeout ->  #Set a timeout and then send element values with Ajax to database to preserve state of element for next time window is opened
            $.ajax(
                type: "PUT"
                url: "/url/to/update/database"
                data:
                    positiontop: top
                    positionleft: left
            )
            ,1000
         )

    setInterval ->
        box.css
            left: (i,v) ->
                newv(v, 37, 39)
            top: (i,v) -> 
                newv(v, 38, 40)
    ,40

2 个答案:

答案 0 :(得分:0)

根据您的评论,您走在正确的轨道上。你必须弄清楚他的代码在做什么。他正在使用您可能不熟悉的ternary operators。我将使用他的返回变量行来帮助解释它。

return n < 0 ? 0 : n > w ? w : n;

这就是说,如果它小于零或大于框宽,则返回n。否则不要管它,因为我们处于边界。在您的情况下,您希望它返回n > 0 or < 100。然后你只需要改变它以%而不是px的形式返回。你可以通过附加'%'来实现。

http://jsfiddle.net/bDMnX/332/

w = 100; //pane.width() - box.width(),

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

我会离开边界,然后递增给你。

答案 1 :(得分:0)

好的,这就是我最终要做的事情。它可能会使用一些调整来使代码更有效,我可能还会使百分比计算值使用一个小数来使div的移动更加平滑。

我遇到了Firefox和Opera的一个问题:在 setInterval-function 中, v 值以像素为单位返回。所以我添加了 v = box [0] .style.left v = box [0] .style.top 来获取在所有浏览器中以百分比形式返回的值。

由于浏览器窗口并不总是正方形,我还添加了另一个函数来分别计算宽度和高度。

JavaScript

var pane = $(window),
    box = $('#box'),
    w = (pane.width() - box.width())/pane.width()*100,
    h = (pane.height() - box.height())/pane.height()*100,
    d = {},
    x = 1;

//Caclulate height movement and window height bounds in %
function newvHeight(v,a,b) {
    v = box[0].style.top  //Grab :top value of the #box div as % in all browsers
    var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
    return (n < 0 ? 0 : n > h ? h : n) + '%';
}

//Calculate width movement and window width bounds in %
function newvWidth(v,a,b) {
    v = box[0].style.left   //Grab :left value of the #box div as % in all browsers
    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 newvWidth(v, 37, 39); },   //Function should set values in %
        top: function(i,v) { return newvHeight(v, 38, 40); }    //here for left and top
    });
}, 20);
相关问题