我有一个页面应该平铺这样的图像
但是当您第一次登陆页面时,您会看到所有图像都堆叠在一起
如果您调整浏览器的大小,它会将所有内容移动到位。这就是我在 jQuery 上的位置,它使这一切发生
jQuery
var colCount = 0;
var colWidth = 300;
var margin = 10;
var spaceLeft = 0;
var windowWidth = 0;
var blocks = [];
$(function(){
$(window).resize(setupBlocks);
});
function setupBlocks() {
windowWidth = $(window).width();
blocks = [];
// 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;
console.log(spaceLeft);
for(var i=0;i<colCount;i++){
blocks.push(margin);
}
positionBlocks();
}
function positionBlocks() {
$('.block').each(function(i){
var min = Array.min(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;
});
}
// Function to get the Min value in Array
Array.min = function(array) {
return Math.min.apply(Math, array);
};
我想一定是我没有正确包装某些东西。
在 HTML 中,我的 <body>
有这个
HTML
<body onload="setupBlocks();">
我的猜测是导致问题的行是这样的
$(function(){
$(window).resize(setupBlocks);
});
我只是用谷歌搜索一下,但我不知道那里叫什么来查看我的其他选项。你能帮我找出这个信息差距吗?
编辑:我从中得到的教程效果很好,因为他对所有项目都进行了手工编码。但在我的项目中,所有内容都被加载到 mustache 模板中。
尽管我可以加载我的脚本 onload
我想,我怎样才能让它在加载时触发,然后在调整大小时再次触发?
最佳答案
页面加载后调用setupBlocks
函数:
$(function(){
setupBlocks();
$(window).resize(setupBlocks);
});
编辑:
查看您的 html 页面,看起来您正在加载页面后动态创建元素。尝试在您的 html 页面中更新此代码:
$(function() {
$.getJSON('img.js', function(data) {
var template = $('#imgtpl').html();
var html = Mustache.to_html(template, data);
$('#image-list').html(html);
setupBlocks();
});
});
关于javascript - 在调整浏览器大小之前,平铺图像的脚本不会初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30566138/