如何在jQuery中获取浏览器滚动位置?

Car*_*los 69 javascript jquery

我有一个带滚动的web文档.我想获得当前滚动位置的值(以像素为单位).当我运行以下函数时,它返回零值.我怎样才能做到这一点?

<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript" src="js/jquery.mousewheel.min.js"></script>
<script type="text/javascript">
    $(function (){
        $('#Eframe').on("mousewheel", function() {
            alert(document.body.scrollDown)
        }
    })
</script>
Run Code Online (Sandbox Code Playgroud)

小智 103

因为看起来你正在使用jQuery,所以这是一个jQuery解决方案.

$(function() {
    $('#Eframe').on("mousewheel", function() {
        alert($(document).scrollTop());
    });
});
Run Code Online (Sandbox Code Playgroud)

这里解释不多.如果你愿意,这里是jQuery文档.

  • 这只是给我0整个时间 (3认同)
  • @Pomster @ r3wt您必须确保将函数设置为滚动的文档对象.因此,如果滚动在某个`<div id ="foo"> ...`上,则语法为`$("#foo").scrollTop()`. (2认同)

Dan*_*non 18

最好使用$(window).scroll()而不是$('#Eframe').on("mousewheel")

$('#Eframe').on("mousewheel") 如果人们使用滚动条上的向上和向下箭头手动滚动或抓取并拖动滚动条本身,则不会触发.

$(window).scroll(function(){
    var scrollPos = $(document).scrollTop();
    console.log(scrollPos);
});
Run Code Online (Sandbox Code Playgroud)

如果#Eframe是一个元素,overflow:scroll并且你想要它的滚动位置.我认为这应该有效(我还没有测试过).

$('#Eframe').scroll(function(){
    var scrollPos = $('#Eframe').scrollTop();
    console.log(scrollPos);
});
Run Code Online (Sandbox Code Playgroud)


Amo*_*mos 6

纯JavaScript可以做到!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
Run Code Online (Sandbox Code Playgroud)