在另一个div中移动一个divsquare(无限循环)

时间:2019-01-13 21:47:15

标签: javascript

只要单击按钮,如何获得一个按钮来移动容器中的正方形? (从左上到左下,从右下,到右上,然后无限地到左上)

我试图制作一个开关盒,但是我有点忘了为完成这项工作可以投入的逻辑。 如果我没有指定任何条件,并且只给按钮提供了一条指令,那么它会起作用

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

但是此代码不是

//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>

1 个答案:

答案 0 :(得分:0)