I'm making a solitaire game in HTML/CSS/JavaScript and I have it so that when you click a card and then another it moves the first card to the same position as the second with the y value shifter 20px. The problem is when I move the first card(king) to the second card(queen) the king is beneath the queen. I would like to make it so that whenever you move a card, that card is put on top.
Here's the relevant code:
var x1 = '';
var x2 = '';
var y1 = '';
var y2 = '';
var img1 = '';
function move(id) {
var id = document.getElementById(id);
Pr('0');
if (img1 == '') {
Pr('1');
img1 = id;
Pr(img1);
var box1 = id.getBoundingClientRect();
x1 = box1.left box1.width * 0.5;
y1 = box1.top box1.height * 0.5;
} else if (img1 != '') {
Pr('2');
img2 = id;
Pr(img2);
var box2 = id.getBoundingClientRect();
x2 = box2.left;
y2 = box2.top 20;
img1.style.cssText = 'left:' x2 'px;top:' y2 'px;';
};
Pr('x1 = ' x1 ' | y1 = ' y1 ' | x2 = ' x2 ' | y2 = ' y2);
};
//Making 'console.print(...)' quicker to type
function Pr(str) {
console.log(str)
};
.card {
height: 100px;
position: fixed;
}
<div style='position:relative;'>
<img class='card' style='left:150px;' id='KD' onclick='move("KD")' src='Cards/Diamonds/K.png'>
<img class='card' id='QD' src="Cards/Diamonds/Q.png" onclick='move("QD")' style=''>
</div>
CodePudding user response:
I figured it out!
var t = 0;
var img1 = '';
var img2 = '';
function move(id){
if (t==0){
img1 = document.getElementById(id);
id1 = id;
t=1;
}else if (t==1){
t=0;
id2 = id;
img2 = document.getElementById(id);
var rect = img1.getBoundingClientRect();
var rect2 = img2.getBoundingClientRect();
var x1 = rect.left rect.width * 0.5;
var y1 = rect.top rect.height * 0.5;
var x2 = rect2.left;
var y2 = rect2.top 20;
img1.style.cssText = 'z-index:2;left:' x2 'px;top:' y2 'px;';
};
};
CodePudding user response:
Apply a z-index
to the image (z-index: 1
should suffice), and each additionally added image needs to get a value higher than the previous one (using some " 1" logic for the value in the script).