用真或假初始化变量是否在 Javascript 中建立了内容的方向

Does initializing a variable with true or false establish the direction of the content in Javascript?

本文关键字:建立 方向 Javascript 初始化 是否 变量      更新时间:2023-09-26
   <script>
     var switchDirection = false;
      function doAnimation() {
        var divAdvert = document.getElementById("divAdvert");
           var currentLeft = divAdvert.offsetLeft;
            var newLocation;
           if (!switchDirection) {
               newLocation = currentLeft + 2;
               if (currentLeft >= 400) {
              switchDirection = true;
              }
          } else {
                  newLocation = currentLeft - 2;
                  if (currentLeft <= 0) {
                  switchDirection = false;
                  }
          }
             divAdvert.style.left = newLocation + "px";
       }
     setInterval(doAnimation, 10);
   </script>

我想知道为什么在函数的开头声明了一个值为 false 的新变量。

不,没有这样的事情。开发人员可能在页面后面使用此变量,因为这是全局变量。他正在从setInterval调用函数,因此它会重复调用。因此,他将该值保留在某个全局变量中,因为如果将其保留在函数中,它将丢失。名称就是这样,只是为了知道变量的意图是什么。它的简单变量。

这条线正在改变位置:- divAdvert.style.left = newLocation + "px";

当 switchDirection 为 false 时,auther 正在增加值:-

if (!switchDirection) {
           newLocation = currentLeft + 2;

一旦超过400,作者更改变量值

  if (currentLeft >= 400) {
          switchDirection = true;
         }

然后他把它移到另一个方向,反之亦然,

     newLocation = currentLeft - 2;
              if (currentLeft <= 0) {
              switchDirection = false;
              }
他/她

没有给值真假,他/她可以使用左边和右边的值或 ltr 和 rtl,但由于他只有 2 个值,他使用了真和假。

它的简单变量,您可以给出任何名称,例如 dir 或 xyz,它将以相同的方式工作。如果你用真改变所有的假和用假代码改变真,也会起作用。