javascript - 如何保持页面底部的元素更新其上方元素的高度以占据所有空间?

标签 javascript jquery css resize chat

您好,我需要为聊天窗口创建一个布局,基本上类似于 Facebook 消息页面上的布局:聊天输入文本框位于窗口底部,消息的滚动内容占据了所有可用空间,看看这张图片:

没有缩小:

enter image description here

然后在缩小时:

enter image description here

聊天输入文本区域始终位于底部,包含消息的滚动 div 的高度会发生变化,即使我按 F12 并出现控制台也是如此: enter image description here

现在我的情况几乎一样,这就是我所做的: 我有这个布局: enter image description here

#top-bar 包含页面的标题,聊天头是聊天框的标题,messages-chat-c​​ontainer 是包含所有消息和#new-message-chat 的滚动条的 div -container 包含文本区域输入。我需要它总是在底部,所以我写了这个 JQuery:

$(function () {
    $(window).resize(function(){
            adjustHeight();
    });

    setTimeout(function() {
            adjustHeight();
    }, 500); 
 });

 function adjustHeight() {
    var header = $("$top-bar");

    var headerHeight = getJQElementHeight(header);
    $(".content").height($(window).height() - headerHeight);

    $("#messages-chat-container").height(getJQElementHeight($(".content")) - getJQElementHeight($("#new-message-chat-container")) );

}

  function getJQElementHeight (selector) {
    return selector.outerHeight(true);
  }

.content 类是包装#chat-head、#messages-chat-c​​ontainer 和#new-message-chat-c​​ontainer 的类。

但它不起作用,或者更好的是,它起作用了,但是 #new-message-chat-c​​ontainer 被剪切了,这意味着它没有全部显示,而只显示了一部分,要查看全部,我必须向下滚动。我希望在底部看到所有内容。

我错过了什么?是否有指南或其他东西可以很好地解释这种技术?

最佳答案

这是一种方法,但如果您愿意,它可能需要 CSS3:

div#top, div#new-message
{
    position: fixed; // or absolute (it depends)
    width: 100%;
    box-sizing: border-box; // this is the css3 bit
    // you need this if you have extra padding and borders and margins
}

div#top
{
    top: 0;
    left: 0;
    height: 80px;
}

div#new-message
{
    bottom: 0;
    left: 0;
    height: 120px;
}

div#chat-messages
{
    padding-top: 80px; // height of the bar on the top
    padding-bottom: 120px; // height of the bar on the bottom
    width: 100%;
}

HTML:

<div id="chat-messages"></div>

<div id="top"></div> <!-- These two are to be above the chat -->
<div id="new-message"></div> <!-- You might want to set a z-index -->

这是示例的链接:http://jsfiddle.net/wk8wB/

根据 w3schools.com,这是 box-sizing: border-box 的含义:

The specified width and height (and min/max properties) on this element determine the border box of the element. That is, any padding or border specified on the element is laid out and drawn inside this specified width and height. The content width and height are calculated by subtracting the border and padding widths of the respective sides from the specified 'width' and 'height' properties

关于javascript - 如何保持页面底部的元素更新其上方元素的高度以占据所有空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22974794/

相关文章:

javascript - Spotify api javascript 验证创建播放列表

javascript - .height() 不是函数 javascript

javascript - <tr> onclick 有效,但我也想要视觉效果

jquery - 在 jQuery 中获取与多个选择器匹配的单个元素

javascript - jQuery.event.handle 未记录且已弃用

android - 如何让 WebView 忽略 css

javascript - SAPUI5 - 对列表项进行分组,而不按升序或降序排序

javascript - 数据表: sorting not working

javascript - 代码镜像每次内容更改时获取当前行号

css - 页面的文本和框中心