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();
};

window.onload=function(){
  resize();
};
function resize(){
  //获取浏览器的宽高,包括适配ie浏览器 
  var winWidth = (window.innerWidth)?window.innerWidth:((document.body) && (document.body.clientWidth))?document.body.clientWidth:0;
  var winHeight = (window.innerHeight)?window.innerHeight:((document.body) && (document.body.clientHeight))?document.body.clientHeight:0;
    
  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>

 这是一个以一张图片为背景图的页面,当浏览器不同大小的时候需要背景图片也跟着按照正常的比例进行缩放,适配。

转载请注明出处:http://www.cnblogs.com/lvxue/p/4049934.html 

posted on 2014-10-25 12:13  前端`sharon  阅读(3133)  评论(2编辑  收藏  举报