简体   繁体   English

使用 jquery 的 .css() 设置“left”属性时遇到问题

[英]Trouble with setting the 'left' property using jquery's .css()

I've been trying to get a 'paddle' to move using the left and right arrow keys.我一直在尝试使用左右箭头键让“桨”移动。 The values change properly whenever I press the left or right keys, and the string seems to be correct, but after the .css() runs, it just returns with the original value.每当我按下左键或右键时,这些值都会正确更改,并且字符串似乎是正确的,但是在 .css() 运行后,它只会返回原始值。 Please help?请帮忙? -- Code used for debugging marked with // -- -- 用于调试的代码标记为 // --

var paddx = 0;
var ball = document.getElementById('ball');
var ballx = 0;
var bally = 0;
var maxw = window.innerWidth;
var maxh = window.innerHeight;
$(document).keydown(function(keyPressed){
    paddle = document.getElementById('paddle');
    var temppaddx = window.getComputedStyle(paddle).getPropertyValue('left');
    paddx = parseInt(temppaddx, 10);
    console.log(temppaddx +" "+ paddx);//
    if (keyPressed.keyCode == 37){
        paddx -= 1;
        if (paddx < 5){
            paddx = 5;
        }
    }
    if (keyPressed.keyCode == 39){
        paddx += 1;
        if (paddx > maxw - 130){
            paddx = maxw - 130;
        }
    }
    temppaddx = paddx.toString(10) + 'px';
    console.log(temppaddx +" "+ paddx);//
    $('paddle').css('left',temppaddx);
    temppaddx = window.getComputedStyle(paddle).getPropertyValue('left');//
    console.log(temppaddx +" "+ paddx);//
});```

You are using document.getElementById('paddle') but also $('paddle') .您正在使用document.getElementById('paddle') $('paddle')

It should be $('#paddle') to make jQuery's selector find the correct element.应该是$('#paddle')使 jQuery 的选择器找到正确的元素。

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

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