问题
I am prepending some data to my page on a button click and instead of just populating immediately on the page, I was wondering if there is a way to animate the prepend()
using slideToggle
or CSS animation.
Here is my current script:
var data = $('.data').html();
var insert = '<div class="data-container">'+ data +'</div>';
$('button').click(function(){
$('.data-container').remove();
$('.initial').prepend(insert);
});
and a JSFiddle
回答1:
You have to do something like this:
var data = $('.data').html();
var insert = '<div class="data-container">'+ data +'</div>';
$('button').click(function(){
$('.data-container').remove();
$('.initial').hide();
$('.initial').prepend(insert);
$('.initial').slideToggle();
});
FIDDLE UPDATED
回答2:
This one liner works great for me, even without the clone()
I'm using it like so:
var elementToPrepend = "<div>Your content</div>";
$(elementToPrepend).hide().prependTo(".prependHere").fadeIn();
Edit: Proper one-liner would be:
$("<div>Your content</div>").hide().prependTo(".prependHere").fadeIn();
Source
回答3:
Like this? http://jsfiddle.net/zR9fN/5/
CSS
/* add display:none; to keep it hidden after being prepended */
.data-container {
display:none;
...
}
jQuery
....
$('.initial').prepend(insert);
$('.data-container').fadeIn('slow'); // fade in the prepended content that was hidden
回答4:
You can animate prepend()
or append()
quite easy. Just pass the whole animated object as a parameter, like so:
$("#container").prepend( $(data).hide().delay(500).show('slow') );
If you like it more readable:
var object = $(data).hide().delay(500).show('slow');
$("#container").prepend(object);
回答5:
var data = $('.data').html();
var insert = '<div id="animationWrapper" style="height: 0"><div class="data-container">'+ data +'</div></div>';
$('button').click(function(){
$('.data-container').remove();
$('.initial').prepend(insert);
jQuery('#animationWrapper').animate({height: '300px'}, 5000, function(){console.log('Yammie!')})
});
Please check the syntax, but this should be a start.
回答6:
You can simply animate before prepending. If you animate it before prepending it will appear with animation.
for example
childContainer.fadeIn(1000);
$(containerElement).prepend(childContainer);
Alternative to fadeIn you can use any animation.
回答7:
I had to do in two lines to get a smooth slideDown animation:
$("<div>Your content</div>").hide().prependTo(".prependHere");
$(".prependHere:first-child").slideDown();
来源:https://stackoverflow.com/questions/24433939/possible-to-animate-jquery-prepend