我一直在尝试使用Pinterest样式布局,并通过之前的StackOverflow讨论找到了这个网站:http://benholland.me/javascript/how-to-build-a-site-that-works-like-pinterest/。
在HTML中创建.block类时,我没有问题,但是我现在尝试在ajax调用的success函数中创建.block类时显示块。
我实际上有一些工作,但我不确定这是不是这样做。
我在document.ready上激活ajax调用,然后在window.load上准备块(Ben Hollands代码),就像这样......
$(document).ready(function() {
start();
function start() {
url="path/to/json/data";
$.ajax({
type: "POST",
url: url,
dataType: "json",
cache: false,
success: function(response){
var result='';
$.each(response, function(k, v){
result += '<div class="block">' + v.text + '</div>';
});
$(".blocks").html(result);
}
});
}
});
然后......
$(window).load(function() {
var colCount = 0;
var colWidth = 0;
var margin = 10;
var spaceLeft = 0;
var windowWidth = 0;
var blocks = [];
setupBlocks();
function setupBlocks() {
windowWidth = $(window).width();
blocks = [];
colWidth = $('.block').outerWidth();
// Calculate the margin so the blocks are evenly spaced within the window
colCount = Math.floor(windowWidth/(colWidth+margin*2));
spaceLeft = (windowWidth - ((colWidth*colCount)+(margin*(colCount-1)))) / 2;
for(var i=0;i<colCount;i++){
blocks.push(margin);
}
positionBlocks();
}
function positionBlocks() {
$('.block').each(function(i){
var min = Math.min.apply(Math, blocks);
var index = $.inArray(min, blocks);
var leftPos = margin+(index*(colWidth+margin));
$(this).css({
'left':(leftPos+spaceLeft)+'px',
'top':min+'px'
});
blocks[index] = min+$(this).outerHeight()+margin;
});
}
});
你觉得怎么样?