سؤال

As a self-improvement exercise I am building a piece of plain js that takes a set of various sized squares (all of the same aspect ratio) and lays them out in a fluid grid so that there are no gaps.

After spending the evening I have a very basic model that works for the test data I have given it.

The last problem I need to solve before I can justify sinking more time in it is this:

When resizing the browser window the width of the parent element (#container) is not being re calculated.
This width is being used with the aspect ratio of the grid items to calculate the row height so when you resize the window everything shifts correctly except the vertical position.

The function being called by window.onresize is as follows

function() {
  var parentElem = this.element;
  console.log(parentElem.offsetWidth);
  var elems = parentElem.getElementsByTagName('*'), i;
  for (i in elems) {
    if((' ' + elems[i].className + ' ').indexOf(' ' + 'tile' + ' ') > -1) {
      var ele = elems[i];
      var tile_size = ele.getAttribute('data-grid-size');
      var tile_col = ele.getAttribute('data-grid-col');
      var tile_row = ele.getAttribute('data-grid-row');
      var col_width = (100 / this.options.cols); // column width in %
      var row_height = (parentElem.getElementWidth() / this.options.cols) / this.options.tile_ratio;
      var left_offset = col_width * tile_col;
      var top_offset = row_height * tile_row;
      // Position tiles
      var currentStyle = ele.getAttribute('style');
      ele.setAttribute('style', currentStyle + ' left: ' + left_offset + '%; top: ' + top_offset + 'px;');
    }
  }
}

See the full fiddle here.

So any ideas as to why the width of the element is not being recalculated?

هل كانت مفيدة؟

المحلول

This line from your fiddle:

window.onresize = gridfill.layoutGrid();

...doesn't assign your function as a resize handler, it calls your function immediately and tries to assign the return value as a resize handler. You need to remove the parentheses:

window.onresize = gridfill.layoutGrid;

Except to keep the correct context within the function you will need to use:

window.onresize = gridfill.layoutGrid.bind(gridfill);

Note that the .bind() function is not supported by IE<=8, but you can use a polyfill, or just wrap the function call:

window.onresize = function() { gridfill.layoutGrid(); };

Demo: http://jsfiddle.net/WzaXF/1/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top