首页 > 解决方案 > Javascript 移动球练习

问题描述

我需要一些帮助来理解上周我的开发训练营让我们完成的练习的解决方案。问题很简单,在对角线轨迹上来回移动“球”(在 html 中的“div”中创建)。下面是解决方案。我无法理解的是最后的“if”语句。根据解,如果球的位置等于 0 或大于由 Xmax 或 Ymax 定义的边缘,则 reverse = !reverse。由于 reverse 最初设置为 false 作为全局变量,这是否意味着如果满足这些条件,则 reverse 的全局值会发生变化?

                      // BALL MOVING EXERCISE (WEEK 2) // 


//Set global variable that would contain the position, velocity and the html element "ball"
// CREATE DIV "BALL" IN HTML - COPY/PASTE TO BODY TAG

  #ball{
    height: 50px;
    width : 50px;
    background : black;
    border-radius : 50%;
    position : absolute;
    left: ;
    top: ;
    }

var positionX = 0;
var positionY = 0;
var velocity = 100;
var reverse = false;
var ball = document.getElementById("ball");

//write a function that can change the position of the html element "ball"
function moveBall() {
  // two x-axis coordinates
  var Xmin = 0;
  var Xmax = 300;

  // two y-axis coordinates
  var Ymin = 0;
  var Ymax = 300;

  if (reverse) {
    positionX = positionX - velocity;
    positionY = positionY - velocity;
    ball.style.left = positionX + "px";
    ball.style.top = positionY + "px";
  } else {
    positionX = positionX + velocity;
    positionY = positionY + velocity;
    ball.style.left = positionX + "px";
    ball.style.top = positionY + "px";
  }

  if (
    positionX > Xmax ||
    positionX === Xmin ||
    positionY > Ymax ||
    positionY === Ymin
  ) {
    reverse = !reverse;
  }
}
setInterval(moveBall, 100);

标签: javascript

解决方案


推荐阅读