【问题标题】:not able to move scroll bar inside a div无法在 div 内移动滚动条
【发布时间】:2017-06-12 10:48:55
【问题描述】:

当用户从表单发送数据时,我有一个动态填充的 div,它类似于聊天框。用户结束消息的位置,该消息显示在 div 内。现在这个 div 有一个滚动条应该保持在底部,但如果用户滚动,那么它应该保持在用户保留它的位置

问题是,虽然滚动条停留在底部,但是当用户将其拉起时,它也会将自己拉到底部,用户无法使用它来滚动。

div 的代码

var youInterval;

function startInterval() {

  youInterval = setInterval(function() {
    var elem = document.getElementById('scrollbody');
    elem.scrollTop = elem.scrollHeight;
  }, 500);

}

document.addEventListener('scroll', function(event) {
  if (event.target.id === 'scrollBottom') {
    clearInterval(youInterval);
  }
}, true);
startInterval();
.chatbox__body {
  overflow-y: auto;
}
<div class="chatbox__body" id="scrollbody"></div>

谁能帮我解决这个问题

【问题讨论】:

  • 在您的滚动事件侦听器中,您检查 ID 为 scrollBottom 的目标,它应该是 scrollbody。

标签: javascript jquery html css scrollbar


【解决方案1】:

你的情况不合格if (event.target.id === 'scrollBottom') {

滚动生成的event在文档上,所以event.target.id实际上是在检查不存在的文档的id属性。

你必须先禁用 body 中的溢出,然后将溢出添加到 div

html,body{  height:100%; width:100%;overflow:hidden;}

.chatbox__body {
  overflow-y: auto;
  height:100%;
}

在您的 JS 中检查 if (event.target.id === 'scrollbody') {

片段

var youInterval;

function startInterval() {

  youInterval = setInterval(function() {
    var elem = document.getElementById('scrollbody');
    elem.scrollTop = elem.scrollHeight;
  }, 500);

}

document.addEventListener('scroll', function(event) {
  debugger;
  if (event.target.id === 'scrollbody') {
    clearInterval(youInterval);
  }
}, true);
startInterval();
html,body{  height:100%; width:100%;overflow:hidden;}
.chatbox__body {
  overflow-y: auto;
  height:100%;
}

#content{
 height:200%;
 width:100%;
 background-color:red;
}
<div class="chatbox__body" id="scrollbody">
  <div id="content"></div>
</div>

【讨论】:

  • 工作得很好,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
相关资源
最近更新 更多