保持图像与动态高度的关系(图像比)

时间:2014-11-24 02:55:44

标签: javascript html css

让我们说我有一个剧院(就像打开脸书图片时那样)当我修改窗户的高度时,我需要图像的宽度以保持关系(因此,图像的高度,因为我根据窗口的高度设置了图像的高度。如果我不够清楚,那么这里是指向小提琴的链接:Fiddle,'因为一段代码片段不仅仅是一句话。

HTML:

<div id="theater">
 <img src="http://www.lametonesdeamor.com/blog/img/caballofelicisimo.jpg" alt=""></img>    
</div>

CSS:

 #theater{
    position:fixed;
 }
 #theater img{
    height:100%
 }

JS(jQuery)根据窗口的高度更新高度

setInterval(function(){ 
$("#theater").height($(window).height()-40);}, 10)

1 个答案:

答案 0 :(得分:1)

在某些浏览器中,设置img的高度不会触发宽度调整。相反,max-width和max-height在这里会有所帮助:

#theater{
    position:fixed;
}
#theater img{
    max-width: 100%;
    max-height: 100%;
}

此外,您可能希望使用$(window).resize而不是每秒100次重置#theater的大小:

function resizeTheater(){ 
  $("#theater").height($(window).height()-40);
}
$(window).resize(resizeTheater);
resizeTheater();

修订JSFiddle:http://jsfiddle.net/kmzq32qd/2/

另外,请注意:对于正确的XHTML语法,img元素应该像<img />一样关闭,而不是像这样<img></img>

&#13;
&#13;
function resizeTheater(){ 
  $("#theater").height($(window).height()-40);
}
$(window).resize(resizeTheater);
resizeTheater();
&#13;
#theater{
    position:fixed;
}
#theater img{
    max-width: 100%;
    max-height: 100%;
}
&#13;
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<div id="theater">
  <img src="http://www.lametonesdeamor.com/blog/img/caballofelicisimo.jpg" alt="" />    
</div>
&#13;
&#13;
&#13;