我在页面中有一个DIV元素,当窗口大小改变时,我想要调整它的大小,但保持正方形纵横比。我想将宽度设置为浏览器宽度的50%,高度等于宽度。我该如何实现?
如果解决方案需要JavaScript,那很好,但我更喜欢不使用jQuery。
我在页面中有一个DIV元素,当窗口大小改变时,我想要调整它的大小,但保持正方形纵横比。我想将宽度设置为浏览器宽度的50%,高度等于宽度。我该如何实现?
如果解决方案需要JavaScript,那很好,但我更喜欢不使用jQuery。
我不确定在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>
window.innerWidth
属性。在那里,您必须使用document.documentElement.clientWidth
。你可以在CSS中将宽度设置为窗口的50%;你只需要调整高度即可-
window.onresize=function(){
var who= document.getElementById('divtoresize');
who.style.height=who.offsetWidth+'px';
}