Je voudrais que le carré bleu clair aille à droite, et que le carré orange descende en même temps. Mais ils vont tous deux en diagonale. Je comprends un peu ce qui se passe ici, mais je ne vois pas pourquoi cela se passe ou comment le réparer. Il semble que les deux appels de fonction affectent les deux éléments. Merci!La fonction javascript pour les éléments en mouvement accède à plus d'éléments qu'il ne le devrait.
jsFiddle: https://jsfiddle.net/8apLsmp7/1/
function moveElem(dir, xPos, yPos, element, index, container){
//Getting width and height of container and item elements
var elem = document.getElementsByClassName(element);
var w = elem[index].offsetWidth;
var h = elem[index].offsetHeight;
var contw = document.getElementById(container).offsetWidth;
var conth = document.getElementById(container).offsetHeight;
var vertEnd = contw - w;
var horiEnd = conth - h;
//clean up variables to make sure they comply with the width and height of the container
if (xPos > vertEnd){
x = vertEnd;
} else if (xPos < 0){
x = 0;
} else {
x = xPos;
}
if (yPos > horiEnd){
y = horiEnd;
} else if (yPos < 0){
y = 0;
} else {
y = yPos;
}
//position the element
elem[index].style.left = x + 'px';
elem[index].style.top = y + 'px';
//set timer, speed and friction
var timer = setInterval(frame, 5);
var spd = 10;
var friction = 0.987;
//what runs every interval
function frame(){
//check if to move right
if (dir === "right"){
if (x >= vertEnd){
clearInterval(timer);
x = vertEnd;
elem[index].style.left = x + 'px';
elem[index].style.top = y + 'px';
} else {
elem[index].style.top = y + 'px';
elem[index].style.left = x + 'px';
x += spd;
spd *= friction;
}
//check if to move left
} else if (dir === "left"){
if (x <= 0){
clearInterval(timer);
x = 0;
elem[index].style.left = x + 'px';
elem[index].style.top = y + 'px';
} else {
elem[index].style.top = y + 'px';
elem[index].style.left = x + 'px';
x -= spd;
spd *= friction;
}
//check if to move up
} else if (dir === "up"){
if (y <= 0){
clearInterval(timer);
y = 0;
elem[index].style.left = x + 'px';
elem[index].style.top = y + 'px';
} else {
elem[index].style.left = x + 'px';
elem[index].style.top = y + 'px';
y -= spd;
spd *= friction;
}
//check if to move down
} else if (dir === "down"){
if (y >= horiEnd){
clearInterval(timer);
y = horiEnd;
elem[index].style.left = x + 'px';
elem[index].style.top = y + 'px';
} else {
elem[index].style.left = x + 'px';
elem[index].style.top = y + 'px';
y += spd;
spd *= friction;
}
}
}
}
moveElem("right", 0, 0, "item", 0, "cont");
moveElem("down", 0, 0, "item", 1, "cont");
Avez-vous essayé d'effectuer un pas/débogage/enregistrement pour voir où les choses vont mal? https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ Voir aussi: https://stackoverflow.com/help/how-to-ask parce que vous n'allez pas obtenir beaucoup de bonnes réponses pour "déboguer mon code pour moi". – jdv
Merci! Mal essayer ceux-là! –