思路:
- 浏览器大小改变会触发JS事件:window.onresize
- 获得浏览器大小 减去 顶部+底部 得到中间区域大小
HTML:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="css/one.css" rel="stylesheet"> <script src="js/one.js" type="text/javascript"></script> </head> <body> <header id="headBlock"></header> <div id="bodyBlock" class="body"></div> <footer id="footBlock"></footer> </body> </html>
CSS:
/* 韦哥说 这里是必须的,这才是真正项目用到的 */ html{ height: 100%: } body{ height: 100%; margin: 0; } /**********************************************/ #headBlock { height: 60px; background-color: red; } #footBlock { height: 60px; background-color: yellow; } .body { background-color: blue; overflow-y: scroll; }
JS:
function reSizeBodyBlock() { "use strict"; var browserHeight = document.documentElement.clientHeight, headHeight = document.getElementById("headBlock").offsetHeight, footHeight = document.getElementById("footBlock").offsetHeight, bodyBlockHeight = (browserHeight - headHeight - footHeight).toString() + "px"; //为什么要加toString()? 因为代码要给更多的人看!!!! document.getElementById("bodyBlock").style.height = bodyBlockHeight; } window.onload = window.onresize = reSizeBodyBlock;
/* ------------------------------------------------------------------ 2015-02-12 17:03:43 ------------------------------------------------------------------ */
更简单灵活的方法:
function initFullBlockBlock() { if (!document.getElementById("full-block")) return; var fullBlockHeight = document.getElementById("full-block").offsetHeight, browserHeight = document.documentElement.clientHeight, bodyHeight = document.getElementsByTagName("body")[0].offsetHeight; bodyBlockHeight = (browserHeight - bodyHeight + fullBlockHeight).toString() + "px"; document.getElementById("full-block").style.height = bodyBlockHeight; }