假设我有一个剧院(就像当你打开 facebook 图像时)并且当我修改窗口的高度时我需要图像的宽度来保持关系(因此图像的高度,因为我有图像的高度设置基于窗口的高度)。如果我不够清楚,这里是 fiddle 的链接: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)
最佳答案
在某些浏览器中设置 img 的高度不会触发宽度的调整。相反,max-width 和 max-height 在这里会有帮助:
#theater{
position:fixed;
}
#theater img{
max-width: 100%;
max-height: 100%;
}
此外,您可能想使用 $(window).resize
而不是每秒重置#theater 100 次的大小:
function resizeTheater(){
$("#theater").height($(window).height()-40);
}
$(window).resize(resizeTheater);
resizeTheater();
修订后的 JSFiddle:http://jsfiddle.net/kmzq32qd/2/
另外,请注意:对于正确的 XHTML 语法,img 元素应该像这样关闭 <img />
而不是像这样<img></img>
function resizeTheater(){
$("#theater").height($(window).height()-40);
}
$(window).resize(resizeTheater);
resizeTheater();
#theater{
position:fixed;
}
#theater img{
max-width: 100%;
max-height: 100%;
}
<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>
关于javascript - 保持图像与动态高度的关系(图像比例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27097184/