问:我如何让每个div逐个消失?

时间:2016-10-24 05:52:02

标签: javascript

所以我有JSON对象,我必须让每个div逐渐消失它们的年龄。

The code so far

JS

var osobe;
getText = function(url, callback) // How can I use this callback?
{
    var request = new XMLHttpRequest();
    request.onreadystatechange = function()
    {
        if (request.readyState == 4 && request.status == 200)
        {
            callback(request.responseText); // Another callback here
        }
    }; 
    request.open('GET', url,true);
    request.send();
}

function mycallback(data) {
   osobe = JSON.parse(data).people;
  anim();
}

getText('http://output.jsbin.com/vawamasaci.json', mycallback);


function anim() {

  var container = document.createElement('div');
  container.id = 'container';
  document.getElementsByTagName('body')[0].appendChild(container);

  for(var key in osobe) {
    var div = document.createElement('div');
    div.innerHTML = osobe[key].name + "<br />";
    div.innerHTML = div.innerHTML + osobe[key].sex;
    div.style.backgroundColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

    var dob_split = osobe[key].dob.split("-");
    var yearOfBirth = dob_split[2];
    var age = new Date().getFullYear() - yearOfBirth;

    animBox(div, age);

    document.getElementById('container').appendChild(div);
  }

  function animBox(div, age){

    var int = setInterval(function() {

      var opacity = div.style.opacity;

      if(opacity != "0") {     
        div.style.opacity = opacity ? (parseFloat(opacity) - 0.1) : 1;
      }

   }, 1000);

   setTimeout(function(){ 

      clearInterval(int);

   }, age * 1000);

  }

}

CSS

#container div {
  width: 100px;
  height: 100px;
  float:left;
}

1 个答案:

答案 0 :(得分:1)

  function animBox(div, age){

   setTimeout(function(){ 

         var int = setInterval(function() {

      var opacity = div.style.opacity;

      if(opacity != "0") {     
        div.style.opacity = opacity ? (parseFloat(opacity) - 0.1) : 1;
      }

     }, 100);
   }, age * 100);

  }

}

希望这会对你有所帮助:)。