Javascript 调整图像大小以填充背景,而不考虑页面高度和宽度(同时保持正确的比率)

Javascript 调整图像大小以填充背景,而不考虑页面高度和宽度(同时保持正确的比率),javascript,css,scaling,Javascript,Css,Scaling,我有一个背景,它在每次加载页面时都是一个随机图像 HTML: <div id="images"> <img id="background" height="100%" width="auto"/> </div> JS: <div id="images"> <img id="background" height="100%" width="auto"/> </div> var-imgs=[“/backgro

我有一个背景,它在每次加载页面时都是一个随机图像

HTML:

<div id="images">
    <img id="background" height="100%" width="auto"/>
</div>
JS:

<div id="images">
    <img id="background" height="100%" width="auto"/>
</div>
var-imgs=[“/backgrounds/1.jpg”、“/backgrounds/2.jpg”、“/backgrounds/3.jpg”、“/backgrounds/4.jpg”、“/backgrounds/5.jpg”]var rand=Math.round(Math.random()*imgs.length)onload=function(){background.src=imgs[rand]}//JavaScript文档

问题是,当图像(不是背景,但在div内)处于横向比例时,由于“最小高度:“100%”而切换到100%,我需要将宽度更改为“自动”,如何实现这一点?干杯,Steff

您可以使用css背景图像并设置:

#background {
    width: 100% !important;
    height: auto;
    min-height: 100%;
    position: fixed;
        top: 0px;
        left: 0px;
    z-index: 1;
}
background-size: cover;