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

标签 javascript html css

假设我有一个剧院(就像当你打开 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/

相关文章:

html - 调整大但不小的图像以适合 html 表格

html - Flexbox 对齐元素拉伸(stretch)问题

html - Internet Explorer 和 Interspire 购物车兼容性问题

javascript - 我如何检查 parent 在 html 中是 span 还是 anchor?

javascript - 让所有网站路径在 express 中加载相同的静态网站

jquery 发现 div 属性更小或更高

css - 使用 Bootstrap 4 Alpha 6 在较小的设备上制作可滚动的居中导航

javascript - 将 Cookie 保存为文件

javascript - 从组件内更改 vue 实例变量

javascript - 为什么这个脚本没有以无限循环结束?