简体   繁体   English

使包装器div缩小动态,响应图像

[英]Make wrapper div shrink around dynamic, responsive image

After countless look-ups, I still can't get an definitive answer. 经过无数次查询后,我仍然无法获得确切的答案。

I need a div to wrap around a responsive image, but the image 我需要一个div环绕响应图像,但是该图像

  • is of unkwown dimensions 尺寸未知
  • should have a height of 70% of wrapper, but the width can be anything, according to dimension ratio. 高度应为包装纸的70%,但宽度可以是任意尺寸,具体取决于尺寸比例。
  • should keep dimension ratio when window sized up and down (at the moment only keeps dimension ratio when scaling up) 放大和缩小窗口时应保持尺寸比例(目前仅在放大时保持尺寸比例)

JSFiddle: http://jsfiddle.net/8c15uw1d/ JSFiddle: http : //jsfiddle.net/8c15uw1d/

div {
height: 60%;
display: inline-block;
border: 2px solid brown;
}
img {
height: 70%;
width:auto:
display: block;
}

Strangely in IE9 this works as required, but in Chrome the image scales up over the div, doesn't 'take it along'. 奇怪的是,在IE9中,此功能可以按要求工作,但在Chrome中,图像会在div上按比例放大,因此无法“顺其自然”。

  1. How do I achieve this? 我该如何实现? I strongly suspect it could only be done with JS. 我强烈怀疑只能用JS完成。

  2. If I indeed need to do this in Jquery (on browser resize) - say I have 100 of these images of 400px x 200px on the page, will site performance be significantly impaired each time the window is resized? 如果确实需要使用Jquery(在调整浏览器大小时)执行此操作-假设我在页面上有100张400px x 200px的图像,那么每次调整窗口大小时,网站性能都会受到严重影响吗? Is this considered bad practise? 这被认为是坏习惯吗?

This is what I came up with: 这是我想出的:

$(window).resize(function () {
    $("div").css("width", ($("img").width() / $(window).width()) * 100 + "%");
});

Since CSS wasn't working perfectly for me, I used JQuery to cater for the width change. 由于CSS不适用于我,因此我使用JQuery来适应宽度变化。

Here is the JSFiddle demo 这是JSFiddle演示

Basically the CSS already lets the image resize as per ration. 基本上,CSS已经允许图像按比例调整大小。 The JQuery code gets the percentage width of the img tag and sets it as the div width in percentage, causing the container to always wrap around the image when the window is resized. JQuery代码获取img标签的百分比宽度,并将其设置为div百分比宽度,从而导致在调整窗口大小时容器始终环绕图像。

I'm not sure if you want the div to shrink in width, but here css for having the ratio kept. 我不确定您是否要使div的宽度缩小,但是在这里使用css来保持比例。 I believe this will scale well on a computer, perhaps not on a mobile device (for 100s of images). 我相信这可以很好地在计算机上扩展,也许不能在移动设备上(用于100幅图像)扩展。 Perhaps consider making it fetch more when scroll reach bottom (like google images search). 也许考虑在滚动到达底部时使其获取更多内容(例如Google图片搜索)。

html, body {
height: 100%;
width: 100%;
}

div {
height: 60%;
display: inline-block;
border: 2px solid brown;
}

img {
max-height: 70%;
max-width: 100%;
width:auto:
display: block;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM