Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更新后自动滚动到DIV底部,仅当更新前已位于DIV底部时_Javascript_Jquery_Html_Dom - Fatal编程技术网

Javascript 更新后自动滚动到DIV底部,仅当更新前已位于DIV底部时

Javascript 更新后自动滚动到DIV底部,仅当更新前已位于DIV底部时,javascript,jquery,html,dom,Javascript,Jquery,Html,Dom,下面的代码将内容添加到DIV,然后滚动以显示新内容: <div id="Scrollable" style="height:400px; overflow:scroll;> 1<br /> 2<br /> 3<br /> 4<br /> </div> <script> // Should DIV be auto scrolled? var autoScroll = true; // Add new conte

下面的代码将内容添加到DIV,然后滚动以显示新内容:

<div id="Scrollable" style="height:400px; overflow:scroll;>
1<br />
2<br />
3<br />
4<br />
</div>

<script>
// Should DIV be auto scrolled?
var autoScroll = true;

// Add new content
$('#Scrollable').append('5<br />6<br />');

if ( autoScroll ){ // Scroll to bottom of DIV
    $('#Scrollable').animate({ scrollTop: $('#Scrollable').prop('scrollHeight') });
}
</script>

您在编写此文件时遇到了哪些问题?下面是一个JSFIDLE示例,基于我在Google中找到的第一个结果“jquery检查div是否滚动到底”。它似乎工作得很好

这是我找到的那篇文章的链接:

编辑:以下是我发布的JSFIDLE的实际代码,以防有人搜索和JSFIDLE消失。有一个id为scrollable的可滚动div(给它一个高度和
overflow-y:scroll
),其中有一个内部div,其中有一个内部div的类。然后,您可以使用以下代码确定div是否滚动到底部:

var scrollable = $('#scrollable');
var inner = $('#scrollable > .inner');

// check if div is scrolled to bottom before addition of new content
var atBottom = Math.abs(inner.offset().top) + scrollable.height() + scrollable.offset().top >= inner.outerHeight();

// add additional content to .inner here

if ( atBottom ) {
  // do stuff like scroll to bottom etc
}

这里有一个很好的例子

如果元素位于滚动的末尾,则以下等价关系返回true;如果元素不在滚动的末尾,则返回false


该页面上列出的演示也非常有用。

我的问题不是如何滚动到底部,而是如何检测DIV何时已滚动到底部
element.scrollHeight - element.scrollTop === element.clientHeight