如何在jQuery中确定窗口的高度和滚动位置?

One*_*yon 178 javascript jquery

我需要在jQuery中获取窗口的高度和滚动偏移量,但我没有在jQuery文档或Google中找到这个运气.

我90%肯定有一种方法来访问一个元素的高度和scrollTop(可能包括窗口),但我找不到具体的参考.

Pim*_*ger 294

来自jQuery Docs:

const height = $(window).height();
const scrollTop = $(window).scrollTop();
Run Code Online (Sandbox Code Playgroud)

http://api.jquery.com/scrollTop/
http://api.jquery.com/height/

  • $(window).height()给出高度视口而不是滚动高度.正如Aidamina建议的那样,$(document).height()给出了真实的滚动高度. (11认同)

Aid*_*ina 41

来自http://api.jquery.com/height/(注意:窗口和文档对象的使用之间的区别)

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document
Run Code Online (Sandbox Code Playgroud)

来自http://api.jquery.com/scrollTop/

$(window).scrollTop() // return the number of pixels scrolled vertically
Run Code Online (Sandbox Code Playgroud)


Kam*_*ski 10

纯JS

window.innerHeight
window.scrollY
Run Code Online (Sandbox Code Playgroud)

比 jquery 快 10 倍以上(并且代码大小相似):

在此处输入图片说明

在这里你可以在你的机器上进行测试:https : //jsperf.com/window-height-width


Joe*_* V. 6

$(window).height()

$(window).width()
Run Code Online (Sandbox Code Playgroud)

还有一个jquery插件来确定元素位置和偏移量

http://plugins.jquery.com/project/dimensions

scroling offset =元素的offsetHeight属性