【发布时间】:2018-04-13 02:52:03
【问题描述】:
我需要使用 CSS 属性 background-image 在容器中呈现图像
这里的问题是我需要呈现每个图像保持它的纵横比,并将图像最大化呈现到容器内居中的图像的height 或width。
HTML:
<div class="fotowind shadow"></div>
编辑:
.fotowind 容器的初始 CSS 属性:
.fotowind {
overflow:hidden;
margin-left:10px;
background:#333;
margin-bottom:5px;
z-index:30;
background-position: center center !important;
background-repeat: no-repeat;
}
根据窗口大小动态构建属性的代码 - 我需要调整图像大小以保持比例,即使是一些空白空间也要保留在两侧:
jQuery:
windowWidth = $(window).width();
windowHeight = $(window).height();
if (windowWidth <= 1200 && windowWidth > 768 || windowHeight < 900)
{
$('.fotowind').css('width', '650px').css('height', '425px');
}
else if (windowWidth > 1200 || windowHeight > 900)
{
$('.fotowind').css('width', '950px').css('height', '650px');
}
if (windowWidth <= 768)
{
$('.fotowind').css('width', '450px').css('height', '425px');
}
生成的 HTML:
<div class="fotowind shadow" style="background-image: url(http://localhost/AdPictures/25/2c/c2/4c/-9/77/1-/4b/77/-b/ff/a-/57/e5/10/2b/31/b1/7516_1_xl.jpg); background-size: 100%; width: 950px; height: 650px; background-position: 50% 50%; background-repeat: no-repeat no-repeat;"></div>
在某些情况下,例如,图像的大小为800x600,我无法以该大小呈现它,或者当图像具有200x650,例如,它变形为容器大小。
【问题讨论】:
-
您需要纯 CSS 解决方案还是可以使用一些 javascript?
-
您好,谢谢。我更喜欢 CSS 解决方案。
-
我推荐使用 CSS (background-size) 这个,查看优秀的文档developer.mozilla.org/en-US/docs/Web/CSS/background-size
标签: javascript jquery html css