【发布时间】:2018-09-06 20:22:16
【问题描述】:
我在我的网页上使用了slimScroll,内容是通过 AJAX 添加的。
如果我向下滚动滚动然后重新加载更多内容(AJAX 加载),滚动条本身始终保持与以前相同的位置。
我想知道slimScroll 是否有任何函数可以在加载新内容后调用以滚动到顶部?
【问题讨论】:
我在我的网页上使用了slimScroll,内容是通过 AJAX 添加的。
如果我向下滚动滚动然后重新加载更多内容(AJAX 加载),滚动条本身始终保持与以前相同的位置。
我想知道slimScroll 是否有任何函数可以在加载新内容后调用以滚动到顶部?
【问题讨论】:
我认为@rochal 描述的scroll 选项现在不会起作用,因为the version currently up on GitHub 似乎没有使用它。请改用scrollTo 或scrollBy。
滚动到顶部:
$('#elem_id').slimScroll({ scrollTo : '0px' });
相反,如果你想滚动到底部,那么以下应该可以工作:
var scrollTo_val = $('#elem_id').prop('scrollHeight') + 'px';
$('#elem_id').slimScroll({ scrollTo : scrollTo_val });
【讨论】:
从 1.0.0 版本开始,如果您需要滚动到顶部,您可以使用 build in scrollTo 方法:
$(element).slimScroll({ scrollTo: '0' });
【讨论】:
此代码已为我运行。
var scrollTo_int = $('#elem_id').prop('scrollHeight') + 'px';
$('#elem_id').slimScroll({scrollTo : scrollTo_int });
这将在底部位置获取滚动条,并在 div 的底部获取内容。
【讨论】:
您也可以使用 javascript 来解决这个问题...
document.getElementById("element-id").scrollTop = document.getElementById("element-id").scrollHeight;
element-id 是您内容区域的id(通常是div)..
当新内容附加到您的 div 时执行此代码
【讨论】:
对我来说,作者@rochal 建议的答案不起作用,scrollTo 和scroll 都不是 slimScroll 配置参数:都是滚动内容而不是句柄,其中一个甚至破坏了容器高度我的情况。
相反,这对我有用:
// let's assume the plugin was initialized with this class name present:
$('.slim-scroll').slimScroll(config);
// then this is the solution.
$('.slimScrollDiv.inQuestion').find('.slimScrollBar').css({ top: 0 }).end().find('.slim-scroll').get(0).scrollTop = 0;
// -----------------------------
// once more, with explanations:
$('.slimScrollDiv.inQuestion') // this is the ‹div› wrapped around our .slim-scroll element by the plugin. It always has the 'slimScrollDiv' class name.
.find('.slimScrollBar') // first address the handle. The order is important because we're going to break the chain at the end.
.css({ top: 0 }) // 'scroll' it.
.end() // stay in the jQuery chain; go back to the last jQuery collection before find().
.find('.slim-scroll') // address the content.
.get(0) // leave jQuery terrain, get the DOM element.
.scrollTop = 0 // scroll it.
;
【讨论】: