简体   繁体   中英

How to animate the ajax/json response?

This is my piece of HTML code

<div class='qna_div'>
    <div class="q_div"></div>
    <div class="a_div"></div>
</div>

I make a Ajax request and get a json response for every click by the user and i append the q_div and a_div using the jquery function

$('.q_div').append(data.question);
$('.a_div').append(data.answer);

I have css keyframe animation on both q_div and a_div to come from right to left of the screen. But the animation works only on the first load of the page and not on the 'append' function for the json response. I am new to css and animations. help me out for the responsive animations

animation in css3 code:

.q_div {
    animation: q_ani 2s;
}

@keyframes q_ani {
    from{margin-left: 50px;}
    to{margin-left: default;}

}

每次需要动画时,都应删除并添加.q_div类

a possible solution using css animation

 $(function() { var cssAnimationEnd = "webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend"; $('.click').click(function() { $('.q_div, .a_div').addClass("animate").one(cssAnimationEnd , function() { $('.q_div, .a_div').removeClass("animate"); }); }); }) 
 .q_div.animate { animation: q_ani 2s; } .a_div.animate { animation: q_ani 2s; } @keyframes q_ani { from { margin-left: 150%; } to { margin-left: default; } } /*for test purpose*/ .q_div, .a_div { position: relative; height: 20px; width: 500px; background: #ddd; margin-top: 10px; } .qna_div { padding: 20px; width: 500px; background: #333; } body { overflow: hidden; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="click">go</button> <div class='qna_div'> <div class="q_div"></div> <div class="a_div"></div> </div> 

You could use jquery to animate your divs. Put this code in the success ajax callback:

 // First put your divs to the right
 $('.q_div, .a_div').css('right','0');
 // Do the animation
 $('.q_div, .a_div').animate({
    left: 0,
 }, 1000);

https://jsfiddle.net/a8cq9yj1/1/

I hope it can help you,i just simple using the classList function and some SASS style rule

http://jsbin.com/vosuvam/2/edit?js,output

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