微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/js/152023.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐