我有一个 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>
谁能帮我解决这个问题
最佳答案
你这里的条件是失败的 if (event.target.id === 'scrollBottom') {
scroll 生成的 event
是在文档上的,所以 event.target.id
实际上是在检查文档的 id
属性,它不存在.
你必须先在 body 中禁用 overflow,然后将 overflow 添加到 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>
关于javascript - 无法在 div 内移动滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44497566/