jQuery animate from CSS “top” to “bottom”

后端 未结 9 1929
北海茫月
北海茫月 2021-01-04 06:49

I\'m looking to animate a div element from an absolute top position to an absolute bottom position on the page load.

The combination of CSS and jQuery code below fai

9条回答
  •  清歌不尽
    2021-01-04 07:29

    I eventually came up with a solution...

    Basically you animate from the old top position to another position also relative to to the top which you calculate by taking the window height and subtracting (1) the desired position from the bottom, and (2) the height of the element you want to animate. Then, at the end of the animation add a callback to change the css so as the element is then position with a bottom value and a top auto value

    Here's the jQuery script:

    $('#click').click(function () {
    
        var windowHeight = $(window).height();
        var lineHeight = $('#line').height();
        var desiredBottom = 100;
    
        var newPosition = windowHeight - (lineHeight + desiredBottom);
    
        $('#line').animate({top:newPosition},1000,function () {
            $('#line').css({
                bottom: desiredBottom,
                top: 'auto'
            });
        });
    
    });
    

    You can see it working in this jsFiddle

提交回复
热议问题