animate max-width in one css class

2019-09-09 03:21发布

问题:

I would like one CSS class that when an element is added to the document.body it would animate in with max-width

currently I know how to do it with two classes and adding the second class after. But I need to add many elements to the page and it would be much cleaner to do it with one class.

Id like to convert this to use one class: http://codepen.io/hellomihai/pen/yYBPjW

css:

.hide-me {
  overflow: hidden;
  max-width: 0;
}

.show-me {
  max-width: 1000px;
  transition: max-width 5s;
}

.my-stuff {
  height: 200px;
  width: 600px;
  background-color: red;
}

html:

$(document).ready(function() {
  var newDiv = document.createElement("div");
  document.body.appendChild(newDiv);
  newDiv.className = 'my-stuff hide-me';
  setTimeout(function() {
    $('.my-stuff').addClass('show-me');
  }, 1);
});

回答1:

Using keyframes you can avoid adding the class the second time like so!

.my-stuff {
  width: 600px;
  height: 200px;
  background-color: red;
  -webkit-animation-name: example;
  -webkit-animation-duration: 4s;
    animation-name: example;
   animation-duration: 4s;
}

@-webkit-keyframes example {
  from {
   width: 0;
  }
  to {
   width: 600px;
  }
}

keyframes example {
  from {
   width: 0;
  }
  to {
   width: 600px;
  }
}

$(document).ready(function() {
  var newDiv = document.createElement("div");
   document.body.appendChild(newDiv);

   // want to not use a setTimeout to add a class after
   setTimeout(function() {
        newDiv.className = 'my-stuff';
  }, 1);
 });


回答2:

There really is no way around that except hiding each div by default and controlling their appearance with classes. I'd advise against that as it would result in more work for the non-animated elements.

div {
    max-width: 0; 
}