网页宽高自适应大小

现在,显示器的分辨率愈来愈多,终端也变得多样化,web开发页面的自适应问题愈来愈多,若是不作处理,一旦显示器的分辨率发生变化,展现的内容可能出现许多意料以外的排版问题。关于不一样终端的展现问题能够经过响应式布局来实现,而不须要响应式布局时咱们须要本身来避免上述问题。css

宽度自适应:html

一、设置最外层容器(如 DIV)的 width 为 100%;web

二、若是网站头部有图片展现,那就不能简单设置宽度为 100%,会出现 repeat 的状况,或者图片大小超出最外层容器宽度,此时能够设置最外层容器宽度为固定值:960px、980px、1000px等,并设置 margin:0 auto ;布局

三、若是以为在较大分辨率的显示器上显示 960px 宽度显得不够大方美观,能够根据不一样的分辨率设置不一样的宽度(一样要设置 margin:0 auto),并制做相应大小的图片替换便可:网站

复制代码
$(function(){
    var screenWidth = window.screen.width;    
    var width;
    var imgURL ;
    if (screenWidth >= 1440) {
        width = "1400px";
        imgURL = "1400.png";
    } else if (1024 < screenWidth && screenWidth < 1440) {
        width = "1200px";
        imgURL = "1200.png";
    } else {
        width = "980px";
        imgURL = "980.png";
    }
    $obj.css("width", width);  //$obj为要设置宽度的jQuery对象
    $img.css("backgroundImage","url(" + imgURL + ")");  //$img为要设置背景的jQuery对象
})    
复制代码

高度自适应:url

一、可直接设置最外层容器以及 html、body 的 height 为 100%;spa

二、有时,网页的填充内容会根据不一样的权限或者数据的完整程度显示出不同的大小,这样,咱们就须要比较页面的大小和显示器的分辨率高度再作相应的调整:code

复制代码
function autoHeight(objId){
    var nowHeight;
    if (window.innerHeight){//FF
        nowHeight = window.innerHeight;
    }else{
        nowHeight = document.documentElement.clientHeight;
    }
    if(nowHeight > document.body.clientHeight){
        document.getElementById(objId).style.height = nowHeight  + 'px';
    }else{
        document.getElementById(objId).style.height = document.body.clientHeight + 'px';
    }
}
复制代码

三、若是页面有页脚(版权信息等),采用状况2的方法可能会使页脚悬于页面中间,这时,页面每每会是 header、main、footer 这样的结构,在外面会有一个外层容器 container,方法2就是设置该外层容器的高度。固然,咱们能够在获取到 container 的新的高度以后减去 header 和 footer 的高度就能够设置 main 的高度了,这样能够避免 footer 出如今页面中间的状况了。htm

此外,咱们还有另外一种方式解决 footer 的问题:position。对象

设置 container 的 position:relative , main 和 footer 的 position:absolute(其他css属性略去):

复制代码
#container{
  position:relative;  
}

#main{
  position:absolute;
  top:80px;    /*header 的高度*/
  bottom:40px;      /*footer 的高度*/
} 

#footer{
  position:absolute;
  bottom:0;
} 
复制代码

 这样结合上面宽度进行设置时,发现设置了 position 以后,margin:0 auto就失效了,由于脱离了文档流的缘故,因此咱们须要设置 container 的 margin-left 为宽度的一半的负值便可,即:

复制代码
$(function(){
    var screenWidth = window.screen.width;    
    var width;
    var imgURL ;
    var left;
    if (screenWidth >= 1440) {
        width = "1400px";
        left = "-700px";
        imgURL = "1400.png";
    } else if (1024 < screenWidth && screenWidth < 1440) {
        width = "1200px";
        left = "-600px";
        imgURL = "1200.png";
    } else {
        width = "980px";
        left = "-490px";
        imgURL = "980.png";
    }
    $obj.css({"width": width,"margin-left":left });  //$obj为要设置宽度的jQuery对象
    $img.css("backgroundImage","url(" + imgURL + ")");  //$img为要设置背景的jQuery对象
})    
复制代码
相关文章
相关标签/搜索