【问题标题】:Setting timeouts for adding classes in a for loop Javascript为在 for 循环 Javascript 中添加类设置超时
【发布时间】:2018-04-04 18:04:05
【问题描述】:

我在我的 for 循环中添加类似 setTimeout 的功能时遇到问题 - 我正在使用它来遍历父 div 的每个子元素,然后同时为每个子元素添加一个类,这会添加一个fadeIn,我想在添加每个类后添加一个延迟

var children = $("#phototitle span");

for (var i = 0; i <= children.length; i++) {
  var x = children[i]
  $("#phototitle span:nth-of-type(" + i + ")").addClass("flip-in-hor-bottom");
  console.log(x);
}

setTimeout 似乎不起作用,它只是将类添加到第一个或最后一个子元素。

谢谢

【问题讨论】:

  • 您的代码没有显示对setTimeout() 的任何使用。另外,请添加相关的 HTML 和 CSS,以便我们重现您的问题并提供可行的解决方案。
  • 您在哪里尝试使用 setTimeout?

标签: javascript jquery for-loop settimeout


【解决方案1】:

您可以创建一个函数,该函数将添加该类并在移至下一个之前设置超时,类似于以下内容:

let children = document.querySelectorAll('.child')

function addClass(className, idx) {

  if (typeof idx === 'undefined') {
    idx = 0
  }
  
  if (children.length>idx) {
    children[idx].classList.add(className)
    setTimeout(function() {
     addClass(className, idx+1)
    }, 1000)
  }
}

addClass('changed')
#container {
 padding: 4px;
 font-family: sans-serif;
}

.child {
  background: #02042e;
  color: white;
}

.changed {
  background: #1010ff;
 }
<div id="container">
  <div class="child">Child One</div>
  <div class="child">Child Two</div>
  <div class="child">Child Three</div>
  <div class="child">Child Four</div>
  <div class="child">Child Five</div>
  <div class="child">Child Six</div>
</div>

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    // Get all elements
    var children = $('#phototitle span');
    
    // For each element
    children.each(function(i, e) {
    
        // Get the element, and sets the delay for the element
        var element = $(e),
            delay   = i * 1000; // One second delay = 1000 ms
    
        // Set the timeout for the element
        setTimeout(delay, function() {
            element.addClass('flip-in-hor-bottom');
        });
    
    });
    

    我认为这样可以解决问题。

    【讨论】:

      【解决方案3】:

      您可以使用以下。它是自调用函数,每 1 秒调用一次,直到 i 变为 children.length(直到遍历所有需要的节点)

      var children = $("#phototitle span");
      
      (function myLoop (i) {  
         setTimeout(function () {   
            $("#phototitle span:nth-of-type(" + i + ")").addClass("white");
            if (i++ < children.length){ 
              myLoop(i); 
            }
         }, 1000)
      })(1);
      .white{
        color: white;
        background-color: black;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div id="phototitle">
        <span>1</span><br />
        <span>2</span><br />
        <span>3</span><br />
        <span>4</span><br />
        <span>5</span>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-25
        • 1970-01-01
        • 2021-11-03
        • 1970-01-01
        • 2020-03-01
        • 1970-01-01
        • 2021-03-07
        • 2017-06-25
        相关资源
        最近更新 更多