如何模拟背景大小:覆盖< img>? [英] How to emulate background-size: cover on <img>?

查看:194
本文介绍了如何模拟背景大小:覆盖< img>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在框内调整图像大小和重新定位,使其覆盖整个框,类似于 background-size:cover 的工作方式。

How can I resize and reposition the image inside a box, in such way that it covers the entire box, similar to how background-size: cover works.

<div class="box" style="width: 100px; height: 100px;">
  <img src="pic.jpg" width="413" height="325">
</div>

我知道我必须添加 overflow:hidden 到框中,图像需要 position:absolute 。但是什么是让我得到正确的图像新尺寸,左+顶位置的公式?

I know I have to add overflow:hidden to the box and the image needs position: absolute. But what's the formula that gets me the right new size for the image, and left + top positions?

推荐答案

这个可能更容易

jQuery

$('.box').each(function() {
    //set size
    var th = $(this).height(),//box height
        tw = $(this).width(),//box width
        im = $(this).children('img'),//image
        ih = im.height(),//inital image height
        iw = im.width();//initial image width
    if (ih>iw) {//if portrait
        im.addClass('ww').removeClass('wh');//set width 100%
    } else {//if landscape
        im.addClass('wh').removeClass('ww');//set height 100%
    }
    //set offset
    var nh = im.height(),//new image height
        nw = im.width(),//new image width
        hd = (nh-th)/2,//half dif img/box height
        wd = (nw-tw)/2;//half dif img/box width
    if (nh<nw) {//if portrait
        im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left
    } else {//if landscape
        im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top
    }
});

css

.box{height:100px;width:100px;overflow:hidden}
.wh{height:100%!important}
.ww{width:100%!important}

这应该处理任何尺寸/方向,不仅会调整大小,还会偏移图像。全部没有相对绝对定位。

This should handle any size/orientation, and will not only resize, but offset the images. All without relative or absolute positioning.

小提琴: http://jsfiddle.net/filever10/W8aLN/

这篇关于如何模拟背景大小:覆盖&lt; img&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆