简体   繁体   中英

How can I animate elements that move due to other nearby elements having $.fadeIn() called on them?

Imagine a horizontal ul of items like this:

Item 1 | Item 2 | Item 4

I wish to insert Item 3 into its appropriate position. If I assume that it is already there, but simply has display: none; , I can call $('.item3').fadeIn() to make it fade in using jQuery.

Unfortunately, doing so makes Item 4 snap to the left/right before Item 3 fades in. Is there a way to cause Item 4 to smoothly animate to make space for the new item?

I have tried using jQuery's show('slide') for this, but it does not seem to play nicely with horizontal ul . I'm also curious about this in general; is there some way to apply the transition property to make any movement of an element smooth?

Minimum Working Example http://jsfiddle.net/L2uh36rc/

Note that when Item 3 fades in and out, Item 4 snaps left or right to accomodate that change. I'd like it to smoothly animate left or right, instead.

One solution possible :

 $( function() { $('#toggle').on('click', function() { var target = $('.target'); var w = target.data('originalWidth'); var curWidth = target.width(); if( target.css('display') === 'none'){ if( ! w ) { w = curWidth; target.data('originalWidth' , w); } target.css({width:0,opacity : 0}).show().animate( { opacity : 1 , width : w + 'px'} , 777 , function(){ $('.target').show(0); } ); }else{ target.animate( { opacity : 0 , width : 0 + 'px'} , 777 , function(){ $('.target').hide(0); } ); }; }); } ); 
 ul li { display: inline-block; overflow : hidden; white-space : nowrap; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Item 1</li> <li>Item 2</li> <li class="target" style="display: none;">Item 3</li> <li>Item 4</li> </ul> <button id="toggle">Toggle Item</button> <div></div> 

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