javascript – Animate /在其他元素消失时轻松放置元素

请看看这个小提琴: http://jsfiddle.net/dhcyA/

尝试点击一个块.我想要的是,当其他元素消失时,所选的块将动画/放松给他的位置,而不是像现在这样跳跃.那么当再次点击框时,相同的动画重复自己,然后再回到位置.

也许要记住:
我使用的是一个reponsive设计,这意味着在缩放窗口之后,这些块可以是垂直和水平的.

小提琴或糖果的任何修改都会很棒!

解决方法

这是我的解决方

在现有的标记上,我添加一个包装器来计算包装器中的框的位置.喜欢这个

<div id="wrapper">
    <div class="block">
        <h2>I'm block 1</h2>
    </div>
    ....
</div>

为了保持块的流畅性,我创建了一个功能来将块定位在包装上.这是块的位置功能

var reposition = function() {
    wrapper = $("#wrapper");
    console.log(wrapper.innerWidth());
    pLeft = 0;
    pTop = 0;
    maxRowHeight = 0;
    $(".block").each(function(){
        if($(this).data('active')) {
            $(this).data('top',pTop);
            $(this).data('left',pLeft);
        } else {
            $(this).stop(0,0).animate({
              'top' : pTop + 'px','left' : pLeft + 'px'
            });
        }
            pLeft += $(this).outerWidth() + parseInt($(this).css('marginLeft'));
            if($(this).height() > maxRowHeight) maxRowHeight = $(this).outerHeight() + parseInt($(this).css('marginTop')); //Find out the longest block on the row

            if(pLeft + $(this).next().outerWidth() + parseInt($(this).next().css('marginLeft')) >= wrapper.innerWidth()) {
               pLeft = 0;
               pTop += maxRowHeight;
               maxRowHeight = 0;
            }

    });    
};

最后,脚本切换块

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

    $(this).siblings().slidetoggle('slow'); //Toggle other blocks

    if(!$(this).data('active')){ //if the block is not active
        $(this).data('left',$(this).position().left); //sets its left
        $(this).data('top',$(this).position().top);   // and top position
        $(this).animate({ //animate at the top and bottom
            top:0,left:0
        },'slow');

        $(this).data('active',true);

    }else{

        $(this).animate({ //animate to its last kNown position
            top:$(this).data('top'),left:$(this).data('left')
        },false);
    }
});

演示

> Demo[Full](调整大小以保持流体性)
> Demo[Full](显示可变高度的版本)

这是解决方案所提供的:

  • Remembers the last position and gradually animate to/from this position
  • Block positions are calculated and animated on load and every resize
  • Repositioning happens on $(window).resize() thus maintaining the fluid nature of the block,despite the use of position absolute
  • Support variable heights
  • Minor change on existing markup & CSS

Also fixed two issues extended by Gaby

  • Accounts for each block margin independently
  • Recalculates the position of the element after resize

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...