调整图像大小时需要更平滑的动画javascript

Want a smoother animation when resizing images javascript

本文关键字:平滑 动画 javascript 图像 小时 调整      更新时间:2023-09-26

我在一个容器中有两个图像。这些图片是上传的,所以我不会提前知道它们的尺寸。我使用这个函数来调整图像的大小以适应它们的容器。调整大小可以很好地工作,但动画是断断续续的。我想知道是否有办法让它看起来更光滑。

$(window).load(function() {
  window.SurveyCreator = new SurveyCreator();
  setTimeout(function() {
    equalheight('.options-container');
  }, 1000);
});
$(window).resize(function() {
  equalheight('.options-container');
});
equalheight = function(container) {
  var currentTallest = 0,
      currentRowStart = 0,
      rowDivs = new Array(),
      $el,
      topPosition = 0;
  $(container).each(function() {
    $el = $(this);
    $($el).height('auto')
    topPostion = $el.position().top;
    if (currentRowStart != topPostion) {
      for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
        rowDivs[currentDiv].height(currentTallest);
      }
      rowDivs.length = 0; // empty the array
      currentRowStart = topPostion;
      currentTallest = $el.height();
      rowDivs.push($el);
    } else {
      rowDivs.push($el);
      currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
    }
    for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
      rowDivs[currentDiv].height(currentTallest);
    }
  });
}

这是html:

<div id="options-box" class="options-box">
  <div class="options-container">
    <img class="question-option" id="question-option-a">
  </div>
  <div class="options-container">
    <img class="question-option" id="question-option-b">
  </div>
</div>

这是css:

.question-option {
    width: 100%;
}
.options-container {
    width: 48%;
    float: left;
    background-color: #F2F1F5;
    padding: 30px;
    text-align: center;
    margin: 0 1%;
    border-radius: 10px;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
}
.options-box {
    margin-top: 25px;
}

尝试在容器的css中添加一个转换。

.options-container {
    transition: 1s;
}

您可能还想添加特定于浏览器的"转换"版本:

.options-container {
    transition: 1s;
    -moz-transition: 1s;
    -webkit-transition: 1s;
    -ms-transition: 1s;
}

此外,要只设置高度动画,请写"高度1s"而不是"1s"。

您是否考虑过将其重构为使用.animate()?如果你要这样做,你可以使用VelocityJS,这会使它更流畅。