正在自己试着写一个瀑布流布局的插件,实现思路和传统的瀑布流思想一样:维护一个高度数组,新元素将被添加在最低的位置,然后更新高度数组。运行后效果正常,通过监听浏览器resize事件重新触发布局,如果容器内元素为添加动画的话效果正常,但是如果元素添加了过渡属性transition
,显示就出现问题了,会出现错位的效果,应该是transition属性造成延迟的问题?该如何解决?
//布局代码,主要就是通过一系列计算获得top和left进行绝对定位
function _init(){
containerWidth = $container.width()
var children = $('.grid')
var gridWidth = children.eq(0).width() + parseInt(children.eq(0).css('margin-left'))
+ parseInt(children.eq(0).css('margin-right')) + parseInt(children.eq(0).css('padding-left'))
+ parseInt(children.eq(0).css('padding-right'))
var columns = Math.floor( containerWidth / gridWidth )
var leftSpace = containerWidth - gridWidth * columns
var offsetArray = []
children.each(function(index, item){
var _height = children.eq(index).height() + parseInt(children.eq(index).css('margin-top'))
+ parseInt(children.eq(index).css('margin-bottom')) + parseInt(children.eq(index).css('padding-top'))
+ parseInt(children.eq(index).css('padding-bottom'))
if(index < columns){
$(item).css({
'position': 'absolute',
'left': index * gridWidth + leftSpace / 2,
'top': children.eq(0).css('margin-top')
})
offsetArray[index] = _height
}else{
var minHeight = Math.min.apply(Math, offsetArray),
minIndex = $.inArray(minHeight, offsetArray)
$(item).css({
'position': 'absolute',
'top': minHeight,
'left': children.eq(minIndex).position().left
})
offsetArray[minIndex] += _height
}
})
}
//监听resize事件重新布局
window.onload = function(){
_init()
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号