javascript-保持元素的宽高比,同时不超过整个页面的最大宽度或高度
作者:互联网
这是“Height equal to dynamic width (CSS fluid layout)”的继续.
我想在保持视频的宽高比的同时最大化视频元素的大小,并且使用前面提到的问题中的大多数答案在宽度方面都做到了这一点.
但是,这是针对单个非滚动网页的.因此,我希望元素在高度过高的情况下自动减小元素的宽度.
我愿意使用JavaScript / jQuery获得此结果,但最好使用纯CSS解决方案.
在下面的示例中,我使用了img hack来强制保持宽高比.
如果高度足够高,一切正常(宽度正常,并且保持宽高比):
问题:
当元素太高时我需要它如何(手动编辑DOM以获取结果):
如您所见,宽度减小了,从而减小了高度以避免滚动条,同时将宽高比保持在16:9.
See jsfiddle to better understand.
的HTML
<script src="https://raw.github.com/flowplayer/flash/master/core/src/javascript/flowplayer.js/flowplayer-3.2.12.min.js">
<div class="top">
<div class="left">
<div id="chat">
chat<br>
chat<br>
chat<br>
chat<br>
chat<br>
chat<br>
chat<br>
chat<br>
chat
</div>
</div>
<div class="right">
<img src="#" width="200" height="58">
</div>
</div>
<div class="video">
<img class="maintain169aspectratio" src="https://dl.dropboxusercontent.com/u/21688/staticlinked/maintain_aspect_ratio_hack.png" />
<div id="player"></div>
</div>
JavaScript(不太相关,但是会生成播放器)
$f("player", "flowplayer-3.2.16.swf", {
clip: {
provider: 'rtmp',
live: true,
url: 'bouvet',
},
plugins: {
rtmp: {
url: "flowplayer.rtmp-3.2.12.swf",
netConnectionUrl: '',
scaling: 'fit',
}
}
});
的CSS
div.video {
position: relative;
margin: 0;
padding-top: 58px;
}
div.video img.maintain169aspectratio {
width: 100%;
}
div#player {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
}
div#chat {
position: relative;
overflow-y: scroll;
width: 100%;
height: 100%;
}
div.top {
position: relative;
width: 100%;
height: 58px;
margin: 0;
}
div.left {
display: table-cell;
width: 100%;
height: 100%;
}
div.right {
display: table-cell;
min-width: 200px;
vertical-align: top;
height: 100%;
}
body {
margin: 0;
}
解决方法:
一种解决方案是使用Grid Stylesheets(GSS).
以下HTML:
<body>
<div id="chat">
Chat
</div>
<div id="preview">
Preview
</div>
<div id="video">
Video
</div>
</body>
可以使用GSS设置样式,如下所示:
@horizontal |[#chat][#preview]| in(body);
@vertical |[#chat][#video]| in(body);
#chat[width] == ::window[width] * 0.5;
#preview[width] == ::window[width] * 0.5;
#chat[height] == #preview[height];
#chat[height] == 100;
#video[center-x] == ::window[center-x];
#video[width] <= ::window[width];
#video[width] == #video[height] * 1.6;
#video[height] == ::window[height] - 100;
但是,只有Firefox 28和Chrome 34或更高版本才支持GSS.
有关完整的解决方案,请查看此Plunker snippet.
标签:aspect-ratio,css,html,javascript 来源: https://codeday.me/bug/20191030/1968094.html