我有一个调整大小的功能,可以使主 div 的大小保持一致。我最初让它根据窗口宽度调整大小,效果很好(函数中的第一个条件)。然后我添加了第二个条件,如果窗口太短,它会根据高度调整大小。此函数与 onload 一起正常工作。
onresize 在窗口变窄或变宽时都适用于宽度,但高度条件仅在窗口变短时有效。. . 如果窗口随后被拖得更高,onresize 事件似乎不会触发,我必须手动重新加载页面以调整函数大小。
<script>
function contentResizeHeight() {
var contentBG = document.getElementById("content");
var windowHeight = window.innerHeight;
var newHeight = Math.round(contentBG.offsetWidth * .6);
if ( windowHeight > newHeight ){
contentBG.style.height = newHeight + "px";
}
if ( windowHeight < newHeight ){
var newerWidth = windowHeight * 1.666666666666666666;
var newerHeight = Math.round(newerWidth * .6);
contentBG.style.height = newerHeight + "px";
contentBG.style.width = newerWidth + "px";
}
};
</script>
#content div 被背景图像覆盖。所以这个想法是保持图像纵横比相同。
div#content{
background-repeat:no-repeat;
background-position:center 0px;
background-size: cover;
min-width:1024px;
max-width:1600px;
min-height:614px;
max-height:960px;
margin-right:auto;
margin-left:auto;
}
我在body标签中调用函数
<body onload="contentResizeHeight()" onresize="contentResizeHeight()">