简体   繁体   中英

Moving a divsquare in another div (infinite loop)

how do I get a button to move a square in the container as long as I click on the button? (from up left to down left, to down right, to up right, then to up left, indefinitely)

I tried to make a switch case but I kinda forget the logic I can put to get this work. If I don't specify any conditions and give only one instruction to the button, it works

   move.onclick = function deplacement() {
        img.style.top = (img.offsetTop + 100) + "px";
        }

But this code doesn't

 //I am not sure if I should define the meaning of the position: let positionUpLeft = img.offsetLeft == 0 px && img.offsetTop == 0 px; let positionBotLeft = img.offsetLeft == 0 px && img.offsetTop == 100 px; let positionBotRight = img.offsetLeft == 100 px && img.offsetTop == 100 px; let positionUpRight = img.offsetLeft == 100 px && img.offsetTop == 100 px; if (positionUpLeft) { move.onclick = function deplacement() { img.style.top = (img.offsetTop + 100) + "px"; positionBotLeft; } } else if (positionBotLeft) { move.onclick = function deplacement() { img.style.left = (img.offsetLeft + 100) + "px"; positionBotRight; } } else if (positionBotRight) { move.onclick = function deplacement() { img.style.top = (img.offsetTop - 100) + "px"; positionUpRight; } } else if (positionHauteDroite) { move.onclick = function deplacement() { img.style.left = (img.offsetLeft - 100) + "px"; positionUpLeft; } } 
 #container { width: 200px; height: 200px; position: relative; background: white; } #img { height: 100px; width: 100px; background-color: blue; border-style: solid; border-color: black; border-width: 1px; position: absolute; } 
 <html> <body> <div id="container"> <div id="img"></div> </div> <br><br> <p><button id="move" type="submit" name="move">move</button></p> </body> </html> 

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.

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