jquery:$(window).scrollTop()但没有$(窗口).scrollBottom()

Bin*_*hen 83 javascript jquery

我想在用户滚动页面时将元素放在页面底部.这就像"固定位置",但我不能使用"position:fixed"css,因为我的许多客户的浏览器都无法支持.

我注意到jquery可以获得当前视口的顶部位置,但是如何才能获得滚动视口的底部?

所以我问如何知道:$(window).scrollBottom()

Dav*_*ang 142

var scrollBottom = $(window).scrollTop() + $(window).height();
Run Code Online (Sandbox Code Playgroud)

  • scroll`Top`是从文档`Top`到可见窗口`Top`的垂直像素数.与滚动"Top"完全相反,滚动"Bottom"应该测量从文档`Bottom`到可见窗口`Bottom`的垂直像素的数量(即下面的Alfred的答案).**this给出的是从文档`_top_`到可见窗口`Bottom`的垂直像素数.它肯定是有用的,虽然不能称之为与ScrollBottom相反(我知道这是一个明显的答案,但对于像我这样的未来读者) (38认同)
  • 你会认为它是否如此简单,它可以作为.scrollBottom()包含在核心框架中.奇怪.. (13认同)

Alf*_*red 84

我会说scrollBottom作为scrollTop的直接对应应该是:

var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
Run Code Online (Sandbox Code Playgroud)

这是一个适合我的小丑陋测试:

// SCROLLTESTER START //
$('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;"></h1>').insertAfter('body');

$(window).scroll(function () {
  var st = $(window).scrollTop();
  var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

  $('#st').replaceWith('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;">scrollTop: ' + st + '<br>scrollBottom: ' + scrollBottom + '</h1>');
});
// SCROLLTESTER END //
Run Code Online (Sandbox Code Playgroud)

  • 太好了,这就是我想要的...谢谢! (2认同)

小智 8

为了将来,我已经将scrollBottom变成了一个jquery插件,可以像scrollTop一样使用(即你可以设置一个数字,它将从页面底部滚动该数量并返回底部的像素数量)的页面,或者,如果没有提供数字,则返回页面底部的像素数)

$.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);
Run Code Online (Sandbox Code Playgroud)