简体   繁体   中英

Slide inner div full height up and down inside outer div

I hope I can describe this well enough, I apologize if it's a little long but I want to be descriptive. This is a simplified version of the problem I'm having on a site I'm currently working on:

I have an inner div inside an outer div- the height of the inner div is not static, sometimes it's height is 'x' pixels while another 'y'. The outer div is a fixed height with overflow:hidden for the overlap of the inner divs, in all cases the inner divs are larger in height than the outer.

My problem is I need to animate the inner div to slide up and down the full height of the inner div so that all of it shows within the outer div. You can see I tried using animate with a percentage here (33% was arbitrary):

http://jsfiddle.net/FLMp8/301/

var stuff = $('#inner1, #inner2');

function runIt() {
    stuff.animate({
        top: '-=33%'
    }, 3000);
    stuff.animate({
        top: '+=33%'
    }, 3000, runIt);
}

runIt();

I can't seem to get it to work uniformly no matter the height however. Any suggestions? Thanks.

Try this,

var stuff = $('#inner1, #inner2');

function runIt() {
    stuff.each(function() {
        $(this).animate({
            top: '0'
        }, 3000);
    });
    stuff.each(function() {
        $(this).animate({
            top: -$(this).height() + $(this).parent('div').height()
        }, 3000, runIt);
    });
}

runIt();

FIDDLE

You can simplify this code as follows

var stuff = $('#inner1, #inner2');

function runIt() {
    stuff.each(function() {
        var $this = $(this);
        $this.animate({
            top: '0'
        }, 3000).animate({
            top: -$this.height() + $this.parent('div').height()
        }, 3000, runIt);
    });
}

runIt();

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