站长论坛

标题: 用JAVASCRIPT实现DIV自动栏高 [打印本页]

作者: superadmin    时间: 2007-9-18 16:24
标题: 用JAVASCRIPT实现DIV自动栏高
在最近的一个项目中遇到一个问题,需要在如下图中的B栏中使用背景,但A和C的高度都是不固定的。标准的CSS+DIV是不支持这种自动高度,想了很多办法,最后找出一个方案,借用JAVASCRIPT来实现!

JAVASCRIPT代码如下:

function init() {
if (document.getElementById) {
var h = document.getElementById("right").scrollHeight-document.getElementById("left_top").scrollHeight;
document.getElementById("left_bottom").style.height = h+"px";
}
}

其中right就是C栏,left_top就是A栏,left_bottom是B栏。基本的原理就是用C栏的scrollHeight减去A栏的scrollHeight,从而得到C栏的高度
将init加到body的onload中就可以了。

演示代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>tzlink.com</title>
<style type="text/css">
<!--
body{
        margin:0px;
}
#container {
        width:700px;
}
#left{
        float:left;
        width:150px;
}
#left_top{
        clear:both;
        width:150px;
        background-color:#FF0000;
        overflow:hidden;
}
#left_bottom{
        width:150px;
        clear:both;
        background-color:#00ff00;
        overflow:hidden;
}
#right{
        width:550px;
        background-color:#0000FF;
        float:left;
}
.clear{
        width:1px;
        height:1px;
        font-size:1px;
        clear:both;
}
p{
        margin:0px;
        padding:5px;
}
-->
</style>
<script type="text/javascript">
<!--
function init() {
        if (document.getElementById) {
                var h = document.getElementById("right").scrollHeight-document.getElementById("left_top").scrollHeight;
                document.getElementById("left_bottom").style.height = h+"px";
        }
}
//-->
</script>
</head>
<body onload="init()">
<div id="container">
        <div id="left">
                <div id="left_top">
                        <p style="font-size:120px">A</p>
                </div>
                <div id="left_bottom">
                        <p style="font-size:120px">B</p>
                </div>
                <div class="clear"></div>
        </div>
        <div id="right">
                        <p style="font-size:500px">C</p>
        </div>
</div>
</body>
</html>





欢迎光临 站长论坛 (http://tzlink.com/bbs/) Powered by Discuz! X3.2