![](/img/trans.png)
[英]Resize embedded videos when window is resized, while keeping aspect ratio
[英]Resize DIV but maintain aspect ratio when window is resized
我的頁面中有一個 DIV 元素,我想在調整 window 大小時調整它的大小,但保持方形縱橫比。 我想將寬度設置為瀏覽器寬度的 50%,高度等於寬度。 我怎樣才能做到這一點?
如果解決方案需要 Javascript 那很好,但我不想使用 jQuery。
在 css 和 window.onresize 事件中使用 width:50% 來調整大小。 看一看
我不確定您是否可以在 CSS 中使一個屬性(高度)等於其他屬性(寬度)...好吧,至少在 CSS 2 中。
但是您當然可以在 JavaScript 中進行此操作。
<div id = "myDiv"></div>
<script>
document.onresize = function() {
var element = document.getElementById('myDiv'); // the element
var size = Math.floor(window.innerWidth / 2) + 'px'; // 50% window width
element.style.width = size; // set the width
element.style.height = size; // set the height
};
</script>
請注意,IE 中不存在window.innerWidth
屬性。 在那里,您必須使用document.documentElement.clientWidth
。
css中可以設置寬度為window的50%; 你只需要調整高度-
window.onresize=function(){
var who= document.getElementById('divtoresize');
who.style.height=who.offsetWidth+'px';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.