首页 文章

保持图像的纵横比,但在达到最大/最小高度时进行裁剪

提问于
浏览
0

我增加但是只会裁剪顶部和底部以保持比率而不是伸展 . 此外,我希望图像高度不会低于200px,只是左右 . 我希望图像永远是中心 . 这是我到目前为止:https://jsfiddle.net/4q83mh41/

<div class="hero">
<img src="http://wpdevserver.x10host.com/wp-content/themes/wp/img/hero1.jpg">
</div>


.hero {
    width: 100%;
    min-height:200px;
    max-height: 650px;
    position: relative;
}
.hero img {
    width: 100%;
    height:auto;
    min-height:200px;
    overflow: hidden;
    max-height: 650px;
    position:aboslute;
}

非常感谢

1 回答

  • 2

    通过添加一些javascript,可以在 .hero div内动态调整图像的位置 . 此外,CSS媒体查询可用于保持图像的宽度正确 .

    .hero {
      width: 100%;
      overflow: hidden;
      max-height: 650px;
    }
    
    .hero img {
      position: relative;
      height: 200px;
      width: auto;
    }
    
    @media (min-width:420px) {
      .hero img {
        width: 100%;
        height: auto;
      }
    }
    

    javascript只是侦听调整大小事件并调整相对定位图像的 topright 属性以使其保持居中 . 请注意,我正在使用JQuery来操作属性 .

    var heroresize = function() {
      var aspect = 1800./858,
          maxheight = 650,
          minheight = 200,
          width = $(".hero").width();
      if(width < minheight*aspect) {
        $(".hero img").css("right",(minheight*aspect - width)/2 + "px");
      } else {
        $(".hero img").css("right","0px");
      }
    
      if(width > maxheight*aspect) {
        $(".hero img").css("top",(maxheight - width/aspect)/2 + "px");
      } else {
        $(".hero img").css("top","0px");
      }
    }
    $(function(){
      heroresize();
      // remove if you don't need dynamic resizing
      $(".hero").on("resize",heroresize);
    });
    

    Javascript可能会导致一些滞后/断断续续,因为调整大小事件可能是性能密集型的 . 如果您不需要担心动态调整大小,可以删除指示的行 .

    我创建了一个可以在这里玩的编解码器:http://codepen.io/regdoug/pen/azxVwd请注意,codepen的最大高度为350px,因为这样可以在不调整大小的情况下查看效果 .

相关问题