0

我正在制作一个非常基本的动画,其中一旦加载并附加到文档中,就会从列表项中删除类。我遇到的问题是动画本身。我希望动画以如下图的方式执行...

我想要的动画

实际上,虽然循环完全运行,console.log 消息以逐步的方式输出,但是一旦循环完成,所有类都会同时被删除。我怎样才能改变这种行为?为什么会逐步执行 console.log 消息,但不会同时执行 classList.remove 功能?

这是我的代码...

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}


/**/
function showListItems() {
  var listItems = document.querySelector('.idList');
  var n = 20;
  var c = 0;
  var itemArray = new Array();
  for (var i = 0; i < listItems.children.length; i++) {
    var item = listItems.children[i];
    if (item.classList && item.classList.contains('idList__item--hide')) {
      console.log('Item: ', item);
      itemArray[c] = item;
      c++;
    }
  }
  console.log('Item Array: ', itemArray);
  itemArray.forEach(function(el, index) {
    sleep(n);
    el.classList.remove('idList__item--hide');
    console.log("EL[" + index + "]: ", el);
  });
}

我意识到这段代码可能看起来很复杂,也许确实如此,但我已经尝试了我能想到的一切。我尝试过使用 Promise、for 循环,现在是 forEach 方法。

谢谢你。

4

3 回答 3

1

这可能是一个不好的方法,但它应该可以解决您的问题。

您可以在 forEach 中使用 setTimeout(),并使用 index 更改时间参数,如下所示:

itemArray.forEach(function(el, index) {
    setTimeout(function(){
         el.classList.remove('idList__item--hide')
    },500*(index+1)) 
});
于 2018-10-29T02:54:47.993 回答
1

在 javascript 完成运行之前,浏览器不会更新。您的脚本在睡眠时不会将控制权交还给浏览器,因此浏览器无法更新。这正是setTimeout它的用途。

改变

itemArray.forEach(function(el, index) {
    sleep(n);
    el.classList.remove('idList__item--hide');
    console.log("EL[" + index + "]: ", el);
});

itemArray.forEach(function(el, index) {
    const ms = n * (index + 1);
    setTimeout(function() {
        el.classList.remove('idList__item--hide');
        console.log("EL[" + index + "]: ", el);
    }, ms);
});

我们remove提前安排了所有的电话,这就是我们n乘以index + 1.

如果您有兴趣,这里是我用来测试sleepvs的代码setTimeouthttps://codepen.io/rockysims/pen/jeJggZ

于 2018-10-29T03:05:22.877 回答
0

我使用 Jquery each 和 setTimeout 函数来链接动画。

$( "li" ).each(function( index ) {
    var listItem = $( this );
    setTimeout(function() {
      listItem.animate({
      opacity: 1
    }, 500); 
    }, (index + 1) * 500);
    
});
ul {
  padding : 20px;
}
ul li {
  list-style : none;
  height : 50px;
  background-color : lightgreen;
  margin : 20px;
  opacity : 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>Hello world 1</li>
<li>Hello world 2</li>
<li>Hello world 3</li>
<li>Hello world 4</li>
</ul>

于 2018-10-29T02:54:11.373 回答