水平和垂直调整一组不同大小的图像 - 需要帮助优化



警告代码在除谷歌浏览器之外的所有内容中崩溃

我正在尝试在我们的网站上创建一个功能,该功能将 8 张随机图像放在两行中,并动态调整图像大小以占据页面的整个宽度。

我为此创建了一个 jsbin 来尝试演示这个问题。

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

代码中的注释应该可以让您很好地了解我在做什么。除了谷歌浏览器之外,所有事情似乎都在发生,而 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
}

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

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

而不是

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

最新更新