javascript - 长宽比填充 - 正确的方法

标签 javascript jquery html

我知道,以前有人问过。尽管答案被标记为正确,但答案仍不充分。

我需要一些东西,通过显示图像的大部分,将其居中并保留其比例,从而用图像填充容器。应该是 ajquery-plugin、一个 Angular-directive 或普通 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 背景大小:封面;背景位置:中心;

关于javascript - 长宽比填充 - 正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34118535/

相关文章:

javascript - Symfony 最佳实践 - 将 Materialise CSS Chips 与 Symfony Forms 结合使用

javascript - (新日期 ('2012-12-01' )).getMonth() === 10?

jquery - 如何自定义 jquery UI Accordion 图标?

php - 如何使用nestable的serialize()保存输入文本

jquery - 使用 jquery 更改 div id

javascript - 是什么导致了这个意外的 Javascript 错误?

javascript - 在客户端使用 Jade 语言,应在服务器端编译而不影响条件

html - 在多个 HTML 页面中重复使用页脚

javascript - 函数不会从 html 内的 onclick 执行

html - 根据容器高度调整元素大小纯 CSS