是否可以在jquery中找到从底部到当前滚动状态的距离

问题描述 投票:0回答:6

假设已向下滚动到网页中间。

是否可以找到距底部的距离(以长度或像素为单位)?

就像当滚动条到达底部时它的值是 0 但如果它距离底部 500px 那么我需要那个 500px 值。

javascript
6个回答
19
投票

对于整个页面:

let scrollPosition = window.pageYOffset;
let windowSize     = window.innerHeight;
let bodyHeight     = document.body.offsetHeight;

alert(Math.max(bodyHeight - (scrollPosition + windowSize), 0));

对于特定元素:

let scrollDistanceTotal      = el.scrollHeight - el.clientHeight;
let scrollDistanceFromBottom = scrollDistanceTotal - el.scrollTop;

5
投票

也试试这个:

$(document).height() - ($('body').height() + $('body').scrollTop())

3
投票

调整 rkleine 的答案。我发现其实是这样的:

$(document).height() - ($(window).height() + $('body').scrollTop())

即$(window) 表示高度而不是 $('body')


2
投票

这是普通 JS 中的代码:

var distanceFromBottom = document.body.scrollHeight - window.innerHeight - window.scrollY

0
投票
var distanceFromBottom = $(document).height() - $(window).height() - $(document).scrollTop();

0
投票

我必须进一步调整以前的答案才能使其发挥作用:

distFromBottom = $(document).height() - $(window).scrollTop() - $(window).height();

只是为了打破它:

let bottomToWinTop = $(document).height() - $(window).scrollTop();

这获取从文档底部到窗口顶部的距离。 由于窗口高度会变化,减去当前窗口高度即可得到距底部的偏移量

let bottomToWinBottom = bottomToWinTop - $(window).height();

现在

bottomToWinBottom = distFromBottom = 0
当用户完全向下滚动页面并向上滚动时,它的值是窗口下方的距离,这可以很好地指示垂直定位。

© www.soinside.com 2019 - 2024. All rights reserved.