简体   繁体   中英

Animate div based on position

I've done the following to animate divs to get a sort of zooming effect.

HTML

<div class='tile-container'>
    <div class='tile'>
        <p>testing</p>
    </div>
    <div class='tile'></div>
    <div class='tile'></div>
    <div class='tile'></div>
    <div class='tile'></div>
    <div class='tile'></div>
    <div class='clearfix'></div>
</div>

JS

$('.tile').click(function(){
    if($(this).hasClass('clicked')){
        return false;
    }

    var itemPosition = $(this).position(),
        containerWidth = ( $('.tile-container').width() / 100 ) * 91,
        containerHeight = ( $('.tile-container').height() / 100 ) * 86,
        clone = $(this).clone();

    $(clone).css({
        'position':'absolute',
        'top': -itemPosition.top,
        'left': itemPosition.left
    }).appendTo('.tile-container').animate({
        width : containerWidth,
        height: containerHeight
    }).children().fadeOut("slow").promise().done(function(){
        $(clone).append("<p class='back'>back</p>").addClass('clicked')
    });
})

$(document).on('click','.back',function(){
    var tile = $(this).parent()
    $(tile).animate({
        width : '50px',
        height: '50px'
    },function(){
        $(tile).remove();
    })
})

CSS

body{
    margin:0px;
    padding:0px;
}
.tile-container{
    background-color:#ccc;
    width:210px;
    height:140px;
}
.tile{
    background-color:blue;
    width:50px;
    height:50px;
    margin:10px;
    float:left;
    cursor:pointer;
}
.clearfix{
    clear:both;
}

The working fiddle

The animation works fine for first left element. How can I manage the rest of the elements with various positions.

You need to animate the top , left property for those divs on the on.click event.

Closest I could get is: jsfiddle .

Just add top:0 and left:0 style to the animate

.appendTo('.tile-container').animate({
        width : containerWidth,
        height: containerHeight,
        'top': 0,
        'left': 0
    })

http://jsfiddle.net/z1xwxan5/13/

If you add top:0 and left:0 to the animate it'll come from the element you want.

animate({
    top : 0,
    left : 0,
    width : containerWidth,
    height: containerHeight
})

To make it go back is a little trickier, but I guess just make itemPosition a global scope variable that gets assigned when you click an element, and then use that to animate top:itemPosition.top and left:itemPosition.left.

Fiddle: 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