jQuery Scroll to bottom of page/iframe

2019-01-02 17:17发布

How do I use jquery to scroll right down to the bottom of an iframe or page?

8条回答
公子世无双
2楼-- · 2019-01-02 17:34

A simple function that jumps (instantly scrolls) to the bottom of the whole page. It uses the built-in .scrollTop(). I haven’t tried to adapt this to work with individual page elements.

function jumpToPageBottom() {
    $('html, body').scrollTop( $(document).height() - $(window).height() );
}
查看更多
泪湿衣
3楼-- · 2019-01-02 17:37

If you don't care about animation, then you don't have to get the height of the element. At least in all the browsers I've tried, if you give scrollTop a number that's bigger than the maximum, it'll just scroll to the bottom. So give it the biggest number possible:

$(myScrollingElement).scrollTop(Number.MAX_SAFE_INTEGER);

If you want to scroll the page, rather than some element with a scrollbar, just make myScrollingElement equal to 'body, html'.

Since I need to do this in several places, I've written a quick and dirty jQuery function to make it more convenient, like this:

(function($) {
  $.fn.scrollToBottom = function() {
    return this.each(function (i, element) {
      $(element).scrollTop(Number.MAX_SAFE_INTEGER);
    });
  };
}(jQuery));

So I can do this when I append a buncho' stuff:

$(myScrollingElement).append(lotsOfHtml).scrollToBottom();
查看更多
人间绝色
4楼-- · 2019-01-02 17:41

scrollTop() returns the number of pixels that are hidden from view from the scrollable area, so giving it:

$(document).height()

will actually overshoot the bottom of the page. For the scroll to actually 'stop' at the bottom of the page, the current height of the browser window needs subtracting. This will allow the use of easing if required, so it becomes:

$('html, body').animate({ 
   scrollTop: $(document).height()-$(window).height()}, 
   1400, 
   "easeOutQuint"
);
查看更多
十年一品温如言
5楼-- · 2019-01-02 17:42

This one worked for me:

var elem = $('#box');
if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {
  // We're at the bottom.
}
查看更多
萌妹纸的霸气范
6楼-- · 2019-01-02 17:44

The scripts mentioned in previous answers, like:

$("body, html").animate({
    scrollTop: $(document).height()
}, 400)

or

$(window).scrollTop($(document).height());

will not work in Chrome and will be jumpy in Safari in case html tag in CSS has overflow: auto; property set. It took me nearly an hour to figure out.

查看更多
呛了眼睛熬了心
7楼-- · 2019-01-02 17:48

For example:

$('html, body').scrollTop($(document).height());
查看更多
登录 后发表回答