简体   繁体   English

jquery位置随着.css()变化而表现得很奇怪

[英]jquery position changing with .css() behaving strange

I tried to make a moving img , and it works partially. 我试图制作一个移动的img ,它可以部分工作。 If I press the right, up or down button, it moves right, up or down. 如果我按向右,向上或向下按钮,它会向右,向上或向下移动。 But, if I press the left button, it jumps very fast very far to the right, and then back to the left and doesn't stop moving (I believe. I said it was fast). 但是,如果我按下左键,它会非常快地跳到右边,然后再向左跳,并且不会停止移动(我相信。我说它很快)。

JSFiddle ; JSFiddle ;
Javascript: 使用Javascript:

$(document).ready(function() {
    var up = down = left = right = false;
    var top = 100, left = 500;
    $("body").on("keydown", function(e) {
        if(e.keyCode == 39) {e.preventDefault(); if (right == false) right = setInterval(moveRight, 80);}
        else if(e.keyCode == 37) {e.preventDefault(); if (left == false) left = setInterval(moveLeft, 80);}
        else if(e.keyCode == 38) {e.preventDefault(); if (up == false) up = setInterval(moveUp, 80);}
        else if(e.keyCode == 40) {e.preventDefault(); if (down == false) down = setInterval(moveDown, 80);}
    });
    $("body").on("keyup", function(e) {
        if(e.keyCode == 39) {clearInterval(right); right = false;}
        else if(e.keyCode == 37) {clearInterval(left); left = false;}
        else if(e.keyCode == 38) {clearInterval(up); up = false;}
        else if(e.keyCode == 40) {clearInterval(down); down = false;}
    });

    function moveUp() {
        top -= 2;
        $("#player").css("top", top + "px");
    }
    function moveDown() {
        top += 2;
        $("#player").css("top", top + "px");
    }
    function moveLeft() {
        left -= 2;
        $("#player").css("left", left + "px");
    }
    function moveRight() {
        left += 2;
        $("#player").css("left", left + "px");
    }
});

This is probably not the best way to do this, I'm open for better suggestions. 这可能不是最好的方法,我愿意接受更好的建议。

You're defining two "left" variables, and they are getting in the way of each other. 你正在定义两个“左”变量,它们正在阻碍彼此。 Change one of their names (perhaps leftInterval for the interval variable), and things should go better. 更改其中一个名称(也许是区间变量的leftInterval),事情应该会更好。

The variables are overwritten, try something like : 变量被覆盖,尝试类似:

$("body").on("keydown", function(e) {
    e.preventDefault();
    var elm = $("#player"),
        top = parseInt(elm.css('top')),
        left = parseInt(elm.css('left'));

    switch(e.which) {
        case 37:
            elm.css("left", left-2);
        break;
        case 38:
            elm.css("top", top-2);
        break;
        case 39:
            elm.css("left", left+2);
        break;
        case 40:
            elm.css("top", top+2);
        break;
    }
});

FIDDLE FIDDLE

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

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