代码之家  ›  专栏  ›  技术社区  ›  One Crayon

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

  •  176
  • One Crayon  · 技术社区  · 16 年前

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

    我90%确定有一种方法可以访问元素(可能包括窗口)的高度和滚动顶部,但我就是找不到具体的引用。

    4 回复  |  直到 8 年前
        1
  •  298
  •   Michał Perłakowski    7 年前

    从jQuery文档:

    const height = $(window).height();
    const scrollTop = $(window).scrollTop();
    

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

        2
  •  41
  •   Aidamina    10 年前

    从…起 http://api.jquery.com/height/

    $(window).height();   // returns height of browser viewport
    $(document).height(); // returns height of HTML document
    

    从…起 http://api.jquery.com/scrollTop/

    $(window).scrollTop() // return the number of pixels scrolled vertically
    
        3
  •  10
  •   Kamil Kiełczewski    6 年前

    纯JS

    window.innerHeight
    window.scrollY
    

    enter image description here

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

        4
  •  6
  •   Omar    11 年前
    $(window).height()
    
    $(window).width()
    

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

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

    滚动偏移=元素的OffsetSight属性

        5
  •  0
  •   dush88c    4 年前

    $('html, body').animate({
                    scrollTop: $("#div1").offset().top
                }, 'slow');