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. 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')
.
It should be $('#paddle')
to make jQuery's selector find the correct element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.