jquery: can i animate the position:absolute to position:relative?

怎甘沉沦 提交于 2019-12-09 04:46:58

问题


i have a bunch of images that are positioned absolutely, i want to be able to click a button and have them all animate to where they would normally be on the page if they had the position: relative.

so is it even possible to animate from position:absolute to position:relative in jquery?

this is what i have:

$(".change_layout").click(function(){

    $(".book_img").animate({position:'relative', top:'0px', left:'0px'}, 1000)

})

回答1:


No, you cannot animate it directly but you can find out the end point and animate the position there. Something like this might work when animation to the static position:

$('img.foo').each(function() {

    var el = $(this);

    // Make it static
    el.css({
        visibility: 'hidden', // Hide it so the position change isn't visible
        position: 'static'
    });

    // Get the static position
    var end = el.position();

    // Turn it back to absolute
    el.css({
        visibility: 'visible', // Show it
        position: 'absolute'
    }).animate({ // Animate to the static position
        top: end.top,
        left: end.left
    }, function() { // Make it static
        $(this).css('position', 'static');
    });
});

It's a bit hacky, but it should work.




回答2:


I don't think you can do that. jQuery animate only works on any "numeric CSS property".




回答3:


No.

However, you could check the element's current location (call .position()), set the position to relative, and animate from the original location to the current one.




回答4:


I like Tatu's solution but found this reusable code to be better for my purposes:

function specialSlide(el, properties, options){
    //http://stackoverflow.com/a/2202831/
    el.css({
        visibility: 'hidden', // Hide it so the position change isn't visible
        position: 'static'
    });
    var origPos = el.position();
    el.css({
        visibility: 'visible', // Unhide it (now that position is 'absolute')
        position: 'absolute',
        top: origPos.top,
        left: origPos.left
    }).animate(properties, options);
}

Let's say I want to slide $('#elementToMove') to a new position, and I want it to take 1000 milliseconds to move. I can call this:

var props = {'top' : 200, 'left' : 300};
var options = {'duration': 1000};
specialSlide($('#elementToMove'), props, options);



回答5:


You can try the css method to make it relative and then animate.

$(".change_layout").click(function(){

    $(".book_img").css({'position': 'relative'}).animate({top:'0px', left:'0px'}, 1000)

})


来源:https://stackoverflow.com/questions/2202749/jquery-can-i-animate-the-positionabsolute-to-positionrelative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!