简体   繁体   中英

How can I make these added divs slide in from the right?

Here's a super simple example I made of creating new divs when you click the spawn button.

http://jsfiddle.net/3fLn9v4e/

jquery

$(document).ready(function()
{
    $('.spawndivs').click(function(){
        var my_div = document.createElement('div');
        my_div.className = 'movingdiv';
        document.getElementById('container').appendChild(my_div); 
    });

    $('#reset').click(function(){
        $('#container').empty();
    });
});

How can I make these divs smoothly slide in from the right hand side up to their resting position when they are created?

You don't need extra js to animate your divs.

Just use keyframes like this:

 $(document).ready(function() { $('.spawndivs').click(function(){ var my_div = document.createElement('div'); my_div.className = 'movingdiv'; document.getElementById('container').appendChild(my_div); }); $('#reset').click(function(){ $('#container').empty(); }); }); 
 body{margin:0px;} .spawndivs { display: inline-block; width: 100px; height: 50px; background-color: gray; float: left; cursor: pointer; text-align: center; margin-bottom:5px; } .container { display: block; background-color: blue; height: 50px; width: 100%; margin-bottom:5px; } .movingdiv { height: 30px; width: 50px; background-color: red; display: inline-block; margin: 10px; animation-duration: 3s; animation-name: slidein; } @keyframes slidein { from { margin-left: -200px; margin-top: 10px; margin-bottom: 10px; margin-right: 10px; } to { margin-left: 10px; margin-top: 10px; margin-bottom: 10px; margin-right: 10px; } } #reset-box{width:100%;clear:left;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="spawndivs"> <p>spawn!</p> </div> <div id="container"></div> <div id="reset-box"><button id="reset">Reset</button></div> 

jsFiddle link: http://jsfiddle.net/AndrewL32/3fLn9v4e/2/

You can use .animate which allow you to perform some animation of an element.

JS

  $(document).ready(function()
  {
      $('.spawndivs').click(function(){
          var my_div = $('<div></div>');
          my_div.addClass('movingdiv');

          my_div
          .appendTo('#container')
          .animate({
            left: "+=20",
            opacity: 1
          });
      });

      $('#reset').click(function(){
          $('#container').empty();
      });
  });

And add a position: relative in your .movingdiv css class.

CSS

.movingdiv
{
    position: relative;
    opacity: 0;
    height: 30px;
    width: 50px;
    background-color: red;
    display: inline-block;
    margin: 10px;
}

You can see the fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM