HTML元素不会保持在底部

时间:2016-04-06 18:42:46

标签: html css

所以我有一个聊天用户界面,这是一个消息框,消息框的底部是一个文本输入元素。它在开始时工作正常,但是一旦出现足够的消息,文本输入元素就会与消息一起向上滚动,并且不会保持在底部。我怎样才能做到这一点?任何有用的想法将不胜感激。

<html>
<body>
<div id="chatui">
<div id="chatmsgs"></div>
<input type="text" id="chatbox">
</div>
</body>
</html>

这是我的CSS:

#chatui {
    z-index:3;
    position:absolute;
    bottom:5px;
    width: 380px;
    height: 150px;
    border: 3px solid #8AC007;
    margin-left:5px;
    overflow:auto;
    }
#chatbox {bottom:3px;position:absolute;width:378px;}
#chatmsgs {position:absolute;}

这是我的Javascript:

这只是当你按下&#34;输入&#34;在键盘上显示您输入的文本&#34; chatmsgs&#34;格。

$(window).keydown(function(e){
if (e.keyCode == 13) {
if (document.activeElement.id == 'chatbox') {
var msg = document.getElementById('chatbox').value;
document.getElementById('chatbox').value = '';  
var ms = '<p>'+msg+'</p>';
$('#chatmsgs').append(ms);
}
}
});

看看这个小提琴,看看我在说什么: https://jsfiddle.net/ev3uymw6/

1 个答案:

答案 0 :(得分:2)

您必须将overflow:auto和相应的height添加到chatmsgs div,以便它不会超出chatui的大小并使其滚动产品总数。

&#13;
&#13;
$(window).keydown(function(e) {
  if (e.keyCode == 13) {
    if (document.activeElement.id == 'chatbox') {
      var msg = document.getElementById('chatbox').value;
      document.getElementById('chatbox').value = '';
      var ms = '<p>' + msg + '</p>';
      $('#chatmsgs').append(ms);
    }
  }
});
&#13;
#chatui {
  z-index: 3;
  position: absolute;
  bottom: 5px;
  width: 380px;
  height: 150px;
  border: 3px solid #8AC007;
  margin-left: 5px;
}
#chatbox {
  bottom: 3px;
  position: absolute;
  width: 378px;
}
#chatmsgs {
  position: absolute;
  height: 130px;
  overflow: auto;
  width: 378px
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="chatui">
    <div id="chatmsgs">
    </div>
    <input type="text" id="chatbox">
  </div>
</body>
&#13;
&#13;
&#13;