I have 2 divs (#1 and #2) and two buttons. When a button is clicked, it should select a div to move and when the arrow keys are pressed, this div should move. The other should remain in its place. If the other button is clicked, the div that had previously moved should remain in its new position and the newly selected div should move along with the arrow keys.
.counter {
border-radius:50%;
width:20px;
height:20px;
position:absolute;
transition:top linear 0.6s, left linear 0.6s;
font-size:20px;
font-weight:bold;
text-align:center;
padding:20px;
top: 525px;
left: 60px;
background-color:red;
}
<button onclick="one">Move One</button>
<button onclick="two">Move Two</button>
<div class="counter" id="1" >1</div>
<div class="counter" id="2">2</div>
var go = "1"
function one() {
go = "1"
}
function two() {
go = "2"
}
document.onkeydown = detectKey;
function detectKey(e) {
var posLeft = document.getElementById('').offsetLeft
var posTop = document.getElementById('').offsetTop
if (e.keyCode == '39') {
if (go === "1") {
document.getElementById('1').style.left = (posLeft+150)+"px"
}
if (e.keyCode == '38') {
document.getElementById('1').style.top = (posTop-150)+"px"
}
}
if (e.keyCode == '39') {
if (go === "2") {
document.getElementById('2').style.left = (posLeft+150)+"px"
}
if (e.keyCode == '38') {
document.getElementById('2').style.top = (posTop-150)+"px"
}
}
}
Aucun commentaire:
Enregistrer un commentaire