动态调整网页上div的高度

时间:2012-05-13 21:05:34

标签: javascript html

我基本上使用网站的3列布局。我想要实现的是中间(内容)列的高度调整到右列(侧边栏),因此中间列右侧的边框到达页面底部。此外,我还希望左列将其高度调整为其他列,并在页面底部填充背景图像单元。

网站:http://www.massageforum.be

这是我到目前为止所做的事情(panel_left =左栏有背景图片,panel_right是div内容(中间栏)和侧栏(右栏)的周围div):

function setDivHeight() {
    //set height of content according to sidebar if content is smaller than sidebar
    var DivHeightSidebar = document.getElementById('sidebar').offsetHeight;
    var DivHeightContent = document.getElementById('content').offsetHeight;

    if(DivHeightContent < DivHeightSidebar)
    {
        document.getElementById('content').style.height = DivHeightSidebar + 'px';
    }           

    //set height of panel_left according to panel_right so background image reaches until bottom of page
    var DivHeight = document.getElementById('panel_right').offsetHeight;
    document.getElementById('panel_left').style.height = DivHeight + 'px';
}

</body>标记之前的每一页上调用此函数。

问题是有时是有效的,但有时不是。在某些情况下,内容列的高度会调整为侧栏列的高度,尽管它应该更长并且内容不再适合。屏幕截图:http://www.massageforum.be/Massageforum1.png

此外,有时左列的高度未正确调整到panel_right的高度。

我在Chrome,Firefox和Safari中看到了这种行为;没有测试其他浏览器。

关于如何使这个功能更健壮的任何建议?

2 个答案:

答案 0 :(得分:1)

用JavaScript做这件事并不是一个好主意。只需重新构建页面并使用HTML / CSS完成所有操作。

答案 1 :(得分:0)

在调用setDivHeight之前,您是否检查过文档是否已完成加载所有元素? 如果在加载元素之前/之前调用该函数,则读取的高度会更小。 我还会考虑将包含列的高度设置为等于容器DIV高度(id ='page2'),它自然地伸展到包含最长的元素。