纵横比填充-正确的方式

Aspect Ratio Fill - the right way

本文关键字:方式 填充      更新时间:2023-09-26

我知道,以前有人问过。这些答案虽然被标记为正确,但并不充分。

我需要一些东西,通过显示图像的大部分来填充容器,使其居中并保持其比例。应该是ajquery插件、angular指令或纯JS。

<div ratio-fill>
  <img>
</div>

当然,在脚本采取行动的地方就足够了。


感兴趣的解决方案:

  <div ratio-fill="http://img.url"></div>

CSS

  *[ratio-fill] { background-size: cover;
    background-position: center; }

脚本(jQuery)

  /* img-ratio-fill */
  $(window).load(function(){
   /* ratio-fill-directive */
   $('*[ratio-fill]').each(function() { 
      var $this = $(this),
          imgUrl = $this.attr( "ratio-fill" );
      $this.css( "background-image", "url('" + imgUrl + "')" );
    });
  })

在div上使用css背景尺寸:封面;背景位置:居中;