jquery: $(window).scrollTop() but no $(window).scrollBottom()

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

I want to place an element to the bottom of the page whenever the user scrolls the page. It's like "fixed position" but I can't use "position: fixed" css as many of my clients' browser can't support that.

I noticed jquery can get current viewport's top position, but how can I get the bottom of the scroll viewport?

So I am asking how to know: $(window).scrollBottom()

回答1:

var scrollBottom = $(window).scrollTop() + $(window).height(); 


回答2:

I would say that a scrollBottom as a direct opposite of scrollTop should be:

var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop(); 

Here is a small ugly test that works for me:

// SCROLLTESTER START // $('

').insertAfter('body'); $(window).scroll(function () { var st = $(window).scrollTop(); var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop(); $('#st').replaceWith('

scrollTop: ' + st + '
scrollBottom: ' + scrollBottom + '

'); }); // SCROLLTESTER END //


回答3:

For the future, I've made scrollBottom into a jquery plugin, usable in the same way that scrollTop is (i.e. you can set a number and it will scroll that amount from the bottom of the page and return the number of pixels from the bottom of the page, or, return the number of pixels from the bottom of the page if no number is provided)

$.fn.scrollBottom = function(scroll){   if(typeof scroll === 'number'){     window.scrollTo(0,$(document).height() - $(window).height() - scroll);     return $(document).height() - $(window).height() - scroll;   } else {     return $(document).height() - $(window).height() - $(window).scrollTop();   } } //Basic Usage $(window).scrollBottom(500); 


回答4:

var scrollBottom =     $(document).height() - $(window).height() - $(window).scrollTop(); 

I think it is better to get bottom scroll.



回答5:

This will scroll to the very top:

$(window).animate({scrollTop: 0}); 

This will scroll to the very bottom:

$(window).animate({scrollTop: $(document).height() + $(window).height()}); 

.. change window to your desired container id or class if necessary (in quotes).



回答6:

Here is the best option scroll to bottom for table grid, it will be scroll to the last row of the table grid :

 $('.add-row-btn').click(function () {      var tempheight = $('#PtsGrid > table').height();      $('#PtsGrid').animate({          scrollTop: tempheight          //scrollTop: $(".scroll-bottom").offset().top      }, 'slow');  }); 


回答7:

This is a quick hack: just assign the scroll value to a very large number. This will ensure that the page is scrolled to the bottom. Using plain javascript:

document.body.scrollTop = 100000; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!