首页 > 代码库 > js 背景图随浏览器大小而变化,且保持图片不变形

js 背景图随浏览器大小而变化,且保持图片不变形

<html><head><style>body{     overflow:hidden;  }#pic{    margin:0 auto;width:100%;height:100%;padding:0;max-width:100%;position:relative;   }#img{  position:absolute;left:0px;top:0px;}</style></head><body>  <div id="pic">      <img src="" id="img" />  </div>   <script type="text/javascript">       window.onresize=function(){        resize();    };    function resize(){      //获取浏览器的宽高,包括适配ie浏览器        if (window.innerWidth)        var winWidth = window.innerWidth;        else if ((document.body) && (document.body.clientWidth))        var winWidth = document.body.clientWidth;        if (window.innerHeight)        var winHeight = window.innerHeight;        else if ((document.body) && (document.body.clientHeight))        var winHeight = document.body.clientHeight;     var bg_rate = parseFloat(1920/990);//图片的宽高比        var br_rate = parseFloat(winWidth/winHeight);//浏览器的宽高比      //根据宽高比的比较,固定图片的宽高来实现图片铺满屏幕而不变形,多余的部分隐藏        if(br_rate<bg_rate){            document.getElementById(img).style.height = winHeight + px             document.getElementById(img).style.width = ‘‘;         }else{            document.getElementById(img).style.width = winWidth + px;            document.getElementById(img).style.height = ‘‘;         }    }</script></body></html>

 

js 背景图随浏览器大小而变化,且保持图片不变形