简体   繁体   English

靠近底部时滚动到div的底部

[英]Scroll to bottom of div when close to bottom

I am working on a chatting service and i need the site to scroll to the bottom of the chatt, and if a person whants to scroll up, the script for scrolling down will stop. 我正在使用聊天服务,我需要将该站点滚动到聊天底部,如果有人想向上滚动,则向下滚动的脚本将停止。 I have the chat inside a div with the id #chat_innhold, and here is my attemnt. 我在一个ID为#chat_innhold的div内进行聊天,这是我的尝试。

window.setInterval(function scrolled(o)
{
        if(o.offsetHeight + o.scrollTop > o.scrollHeight - 75)
        {
            window.setInterval=function()
                {
                return false;
                }
        }
        else
        {
            window.setInterval=function()
                {
                $("html, #chat_innhold").animate({ scrollTop: $('#chat_innhold').prop("scrollHeight")}, 'slow');
                }
        }
}, 1000);

When i am 75 pixels above bottom, a want to stop the scroll to bottom function. 当我在底部上方75像素时,想要停止滚动到底部功能。

为什么要覆盖window.setInterval?

If I understood correctly, you need something like that 如果我理解正确,则需要类似的东西

<div class="wrapper">
  <button>Go to bottom</button>
  <button class="go-top">Go to top</button>
</div>

body,
.wrapper {
  margin: 0;
  padding: 0;
}
.wrapper {
  position: relative;
  height: 1000px;
}
.go-top {
     bottom: 0;
    position: absolute;
    left: 0;
}

var elem = $('.wrapper')[0];
if (elem.addEventListener) {
  if ('onWheel' in document) {
    // IE9+, FF17+, Ch31+
    elem.addEventListener("wheel", onWheel);
  } else if ('onmousewheel' in document) {
    // old variant
    elem.addEventListener("mousewheel", onWheel);
  } else {
    // Firefox < 17
    elem.addEventListener("MozMousePixelScroll", onWheel);
  }
} else { // IE8-
  elem.attachEvent("onmousewheel", onWheel);
}

function onWheel(e) {
  e = e || window.event;
  var delta = e.deltaY || e.detail || e.wheelDelta;
    if(delta < 0 || delta > 0) {
        $('html, body').stop();
  }
}

var deltaWindowBodyHeight = $('body').height() - $(window).height();

function goToBottom() {
  $('html, body').animate({
        scrollTop: deltaWindowBodyHeight - 75
    }, 1000);
}
function goToTop() {
  $('html, body').animate({
        scrollTop: 0
    }, 1000);
}
$('button').click(function() {
if($(this).hasClass('go-top')) {
    goToTop();
} else {
    goToBottom();
}
});

JSFiddle example JSFiddle示例

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

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