javascript - 在调整浏览器大小之前,平铺图像的脚本不会初始化

标签 javascript jquery

我有一个页面应该平铺这样的图像

enter image description here

但是当您第一次登陆页面时,您会看到所有图像都堆叠在一起

enter image description here

如果您调整浏览器的大小,它会将所有内容移动到位。这就是我在 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/

相关文章:

javascript - 无法读取未定义的属性 'force'(简单 D3 网络图)

javascript - 这些函数将以什么顺序执行?

jquery - 单击 HTML 元素并生成弹出窗口

javascript - 使用窗口调整大小功能来保持变量最新?

javascript - 自定义 Google Plus One (+1) 图片之前/之后

javascript - AngularJS 和 JSON 数组

javascript - 通过数学随机函数增加输入值

javascript - 如何将这些信息放入变量中?

jquery - 我们可以使用 jquery 编辑元素的现有类吗?

javascript - 从左向右滑动 LI 无需滚动 CSS 或 JS?