简体   繁体   English

如何用百分比方向键移动div

[英]How to move a div with arrow keys in percent

I got this script from another question here on stackoverflow and it works perfectly. 我从另一个关于stackoverflow的问题中获得了此脚本,它运行良好。 The script updates the element in px, and I specially like the way you can move the element diagonally by holding up+left arrow keys for instance. 该脚本以px为单位更新元素,我特别喜欢通过按住向上和向左箭头键的方式对角移动元素的方式。

My question now is: Is it possible to change the script so it sets and updates values of the element in percent instead? 现在我的问题是:是否可以更改脚本,以便它以百分比形式设置和更新元素的值?

The reason for this is that I'm developing a site with responsive design and I need the elements to stay (and move) on the page relative to the window size. 这样做的原因是,我正在开发具有响应设计的网站,并且我需要相对于窗口大小在页面上停留(和移动)的元素。 I have tried to figure it out, but no success so far. 我试图弄清楚,但到目前为止没有成功。

Here is the script: 这是脚本:

HTML 的HTML

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

CSS 的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 的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

You are on the right track according to your comment. 根据您的评论,您走在正确的轨道上。 You have to figure out what his code is doing. 您必须弄清楚他的代码在做什么。 He is using ternary operators which you may not be familiar with. 他正在使用您可能不熟悉的三元运算符 I will use his return variable line to help explain it. 我将使用他的返回变量行来帮助解释它。

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

This says, return n if it is less than zero or greater than the box width. 也就是说,如果n小于零或大于框的宽度,则返回n。 Otherwise leave it alone because we are at a boundary. 否则就别管它了,因为我们处在边界。 In your case you would want it to return n > 0 or < 100 . 在您的情况下,您希望它返回n > 0 or < 100 Then you just need to change it to return in terms of % instead of px. 然后,您只需要更改它即可返回%而不是px。 You do that by appending '%'. 您可以通过添加'%'来实现。

http://jsfiddle.net/bDMnX/332/ 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) + '%';
}

I will leave getting the bounding and incrementing up to you. 我将离开边界并逐步增加。

Ok, this is what I ended up doing. 好的,这就是我最终要做的。 It probably can use some tweaking to make the code more efficient, and I probably also will make the percent calculation values use one decimal to make the moving of the div more smoother. 它可能可以使用一些调整来使代码更有效,并且我也可能会使百分比计算值使用小数点后一位来使div的移动更加平滑。

I ran into one problem with Firefox and Opera: In the setInterval-function the v value is returned in pixels. 我遇到了Firefox和Opera的一个问题:在setInterval-function中 ,以像素为单位返回v值。 So I added the v = box[0].style.left and v = box[0].style.top to get the value returned as percent in all browsers. 因此,我添加了v = box [0] .style.leftv = box [0] .style.top以获取在所有浏览器中返回的百分比值。

Since the browser window isn't always a square, I also added another function to calculate the width and height separately. 由于浏览器窗口并不总是正方形,因此我还添加了另一个函数来分别计算宽度和高度。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM