如何获得最大文档滚动值
我正在制作一些插件,我需要获得文档的最大scrollTop
值。 最大scrollTop
值是2001
,但$(document).height()
返回2668
和$('body')[0].scrollHeight
给我undefined
。
如何通过javascript / jquery获取2001
?!
您的评论中的代码应该有效:
$(document).height() - $(window).height()
这是一个示例,当您滚动到最大滚动位置时会发出警报: http : //jsfiddle.net/DWn7Z/
如果要“猜测”最大滚动值,可能应该比较文档的高度和视口高度(窗口大小)。
/** * Return a viewport object (width and height) */ function viewport() { var e = window, a = 'inner'; if (!('innerWidth' in window)) { a = 'client'; e = document.documentElement || document.body; } return { width : e[ a+'Width' ] , height : e[ a+'Height' ] } } // Retrieve the height of the document, including padding, margin and border var documentHeight = $(document).outerheight(true); var viewPortData = viewport(); var maxScrollTop = documentHeight - viewPortData.height;
当然,在你的插件中,你还应该在resize事件上添加一个监听器,并重新计算最大的scrollTop。
在vanilla Javascript中,我目前正在这样做:
getScrollTopMax = function () { var ref; return (ref = document.scrollingElement.scrollTopMax) != null ? ref : (document.scrollingElement.scrollHeight - document.documentElement.clientHeight); };
这将返回Gecko的非标准scrollTopMax(如果存在),否则计算它。 我在这里使用document.scrollingElement
,它只存在于特定的浏览器上,但很容易填充 。
这是我写的一个答案https://stackoverflow.com/a/48246003/7668448 ,它是关于scrollTopMax的polyfill,它是Element对象的本机属性。 (只有mozilla)。 看看响应,你真的很喜欢它。
贝娄只是一个快速的片段。 链接中的答案更丰富(请务必查看)。
(function(elmProto){ if ('scrollTopMax' in elmProto) { return; } Object.defineProperties(elmProto, { 'scrollTopMax': { get: function scrollTopMax() { return this.scrollHeight - this.clientTop; } }, 'scrollLeftMax': { get: function scrollLeftMax() { return this.scrollWidth - this.clientLeft; } } }); } )(Element.prototype);
使用示例:
var el = document.getElementById('el1'); var max = el.scrollLeftMax;