HTML5 footer固定的解决方案

最近遇上个郁闷的事,前端妹纸离职去了驴妈妈旅游网,本来手里安卓和后端的活就来不及干,这下好了,前端离职,自己就得兼任前端,遇坑填坑吧。

<body>

    <header></header>//头

    <article></article>//内容

    <footer></footer>//尾

    <div></div>//隐藏层,用于显示加载效果

</body>

主要坑爹的地方在于没有考虑窗口的高度,她的body设置如下

/* general style */
body, p, label, input{margin: 0;padding: 0;}
body{background-color: #edeef0;}

 

然后给footer设置了如下属性

footer{margin-top: 10%}
footer p{color: #BCBCBC;font-size: 12px;text-align: center;}

 

造成的后果就是尾部的公司名称显示位置不正确,在内容过少时而窗口高度很高时,公司名称显示在整个垂直高度的中间位置,但如果给footer

的position设为fixed的话,在内容过多而窗口高度很小时,底部公司名称一直固定在窗口底部,遮盖了页面内容。

我想了两种方案一种是media queries,另一种是js,但是作为一个非专业的前端,我还是选择了后者,感觉后者会比较容易。

 

整体布局不变,将height改为100%
html,body {margin: 0;padding:0;height: 100%;background-color: #edeef0; }

 

footer默认position为fixed,并且外边距设为0
footer{width:100%; position:fixed;bottom:0;}
footer p{color: #BCBCBC;font-size: 12px;text-align: center;}

接下来就是js操作

 

//浏览器视窗的高度
function getWindowHeight(){
var windowHeight = 0;
     if(document.compatMode == "CSS1Compat"){//BackCompat:标准兼容模式关闭。 CSS1Compat:标准兼容模式开启
         windowHeight = document.documentElement.clientHeight;
     }
     else {
         windowHeight = document.body.clientHeight;
     }
     return windowHeight;
}

//获取所有内容高度
function getAllDivHeight(){
    var height = 0;
    height=$("footer").outerHeight(true)+$("article").outerHeight(true)+$("header").outerHeight(true);
    return height;
}

//页面加载时

$(document).ready(function(){
    $(".error p").text(getWindowHeight()+"........"+getAllDivHeight());//显示高度使用
    $(".error").css("visibility", "visible");
    //判断大小,修改长度
    if((getWindowHeight()  - getAllDivHeight()) > 0)
        $('footer').css('position','fixed');
    else
        $('footer').css('position','relative');
});

 

除了以上js,还有一个比较容易被遗忘的地方,手机上webview加载该页面后,点击输入框,会弹出个输入法,造成

高度变化,所以也要监听状态变化做处理

//监听窗口变化
window.onresize = function(){
    $(".error p").text(getScrollHeight()+"......"+getWindowHeight()+"........"+getAllDivHeight());
    $(".error").css("visibility", "visible");
    //滑到底部时footer定于最下方,假定<footer>的height为60
    if((getWindowHeight()  - getAllDivHeight()) > 0)
        $('footer').css('position','fixed');
    else
        $('footer').css('position','relative');
}

完成以上代码后,footer中的内容就跟着高度自适应啦,虽然是非专业前端,但是media queries还是要抽空学习下才行的。

在窗口高度421,内容高度392时,footer定位为fixed

 

当窗口高度216,内容高度392时,footer定位变成relative

 

posted @ 2016-03-18 23:24  六月飞鸟  阅读(834)  评论(0编辑  收藏  举报