水平和放大一组可变大小的图像。垂直 - 需要帮助优化

时间:2017-11-13 18:43:37

标签: javascript jquery html css

警告代码崩溃除了Google Chrome之外的所有内容

我试图在我们的网站上创建一个功能,该功能需要8个随机图像并将它们分成两行,并动态调整图像大小以占据页面的整个宽度。

我为此创建了一个jsbin,试图证明这个问题。

https://jsbin.com/yijemazovi/edit?html,css,js,output

代码中的注释应该让您对我正在做的事情有一个很好的了解。除了谷歌Chrome之外,其他所有事情似乎都在发生,因为while条件永远不会满足,所以它会无限地继续下去并导致浏览器崩溃。

也许这就像我正在做的do / while循环一样简单,或者我应该只使用while循环???

感谢任何帮助!

/*****
 * Get the overall width of the container that we want to match
 **********/
var ContainerWidth = $('.feature-inim-collage .col.span_1_of_1').width();


/*****
 * Increase the height of the images until the total sum of the width 
 * if the 4 images + the gutters is larger than ContainerWidth - then 
 * stop
 **********/

/*****
 * Increment in jumps of 10px until we get within 80% of the width of 
 * the ContainerWidth and then go to a more precise increment of 1px.
 * We can increase the px from 10 to 20 or 30 so there are less loops
 * but this can cause issues when we look at mobile and there is less
 * overall width in the containers and jumping by 30px will be too much
 **********/
var i = 0;
do {
  $('.feature-inims-top-row .growable-container').css('height', i);
  var RowWidth1 = CalculateTotalWidth(1);
  if(RowWidth1 < (ContainerWidth*0.8)){
    i = i+10;
  }else{
    i++;
  }
}
while (RowWidth1 < (ContainerWidth - 3));

/*****
 * Repeat above for the 2nd row
 **********/
var i = 0;
do {
  $('.feature-inims-bottom-row .growable-container').css('height', i);
  var RowWidth2 = CalculateTotalWidth(2);
  if(RowWidth2 < (ContainerWidth*0.8)){
    i = i+10;
  }else{
    i++;
  }
}
while (RowWidth2 < (ContainerWidth - 3));

/*********
 * Calculate the combined width of the images + the gutters
 ****/
function CalculateTotalWidth(Row) {
  var Image1Width = $('.growable-container-1').width();
  var Image2Width = $('.growable-container-2').width();
  var Image3Width = $('.growable-container-3').width();
  var Image4Width = $('.growable-container-4').width();
  var Image5Width = $('.growable-container-5').width();
  var Image6Width = $('.growable-container-6').width();
  var Image7Width = $('.growable-container-7').width();
  var Image8Width = $('.growable-container-8').width();
  var GutterSize = 24; // (3 gutters @ 8px each)

  if(Row == 1){
    var RowWidth = GutterSize + Image1Width + Image2Width + Image3Width + Image4Width;
  }else{
    var RowWidth = GutterSize + Image5Width + Image6Width + Image7Width + Image8Width;
  }
  return RowWidth
}

1 个答案:

答案 0 :(得分:1)

事实证明这个问题是在CalculateTotalWidth()函数中我检查了图像所在容器的宽度而不是图像本身。一旦我改变它,它就完美地运作了。

var Image1Width = $('.growable-container-1 img').width();

而不是

var Image1Width = $('.growable-container-1').width();