简体   繁体   English

Javascript 自动滚动 div 内容,同时仍然可以手动滚动

[英]Javascript auto scroll div content while still being able to manually scroll

window.setInterval(function() {
var elem = document.getElementById('pullout');
elem.scrollTop = elem.scrollHeight;
}, 0);

Im currently using this code to scroll automatically to the bottem.我目前正在使用此代码自动滚动到底部。 But whenever I want to scroll manualy, I simply can't.但是每当我想手动滚动时,我就是做不到。 Because thats how this code above works.因为上面的代码就是这样工作的。 Can someone help me with this?有人可以帮我弄这个吗?

I want the code above + being able to manualy scroll and disable the automatic scroll.我想要上面的代码+能够手动滚动并禁用自动滚动。 But how do I code that?但是我该如何编码呢?

You set the interval but it never stop. 您设置间隔但它永远不会停止。 So whenever you try to scroll, the interval sets it back to the bottom. 因此,无论何时尝试滚动,间隔都会将其设置回底部。 Given that your interval is 0ms, your code is faster than you when it comes to scroll. 假设你的间隔是0ms,你的代码比滚动时更快。 to solve the problem, you simply have to remove the setInterval . 要解决这个问题,您只需删除setInterval Maybe you are attempting to implement smooth scrolling; 也许你正试图实现平滑滚动; if its the case, you are wrong as your code simply automatically scrolls to the bottom. 如果是这样的话,你错了,因为你的代码只是自动滚动到底部。 Simply use: 只需使用:

 function funcName(){
   var elem = document.getElementById('pullout');
   elem.scrollTop = elem.scrollHeight; 
  }

Instead of scrolling continuously, I would only scroll when a new chat message is added. 我只会在添加新聊天消息时滚动,而不是连续滚动。 Something like this: 像这样的东西:

function scrollToBottom() {
    var elem = document.getElementById('pullout');
    elem.scrollTop = elem.scrollHeight;
}

Then, find your code that adds a new chat message, and call scrollToBottom() after the message is added. 然后,找到添加新聊天消息的代码,并在添加消息后调用scrollToBottom()

setInterval repeatedly executes the callback provided . setInterval重复执行提供的回调 An alternative is to use requestAnimationFrame which is a "1 shot" callback :另一种方法是使用requestAnimationFrame ,它是一个“一次性”回调

window.requestAnimationFrame(function() {
var elem = document.getElementById('pullout');
elem.scrollTop = elem.scrollHeight;
}, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM