javascript 滚动时如何获取div顶部位置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12502769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:22:11  来源:igfitidea点击:

How to get the div top position value while scrolling

javascriptjqueryjavascript-events

提问by rex

I am trying to run some script when div reaches to a certain point when it's scrolled. There is a fixed navigation and when the user scrolls the window it suppose change the nav name once it reaches close to the nav. I am using the $(window).scroll function but it only checking the div position once and not updating the value. How to make scroll check the window size every 5-10 px move so that it doesn't take too much memory/processing. The code is set up at: http://jsfiddle.net/rexonms/hyMxq/

当 div 滚动到某个点时,我试图运行一些脚本。有一个固定的导航,当用户滚动窗口时,它假设在接近导航时更改导航名称。我正在使用 $(window).scroll 函数,但它只检查一次 div 位置而不更新值。如何让滚动检查每移动 5-10 像素的窗口大小,以免占用太多内存/处理。代码设置在:http: //jsfiddle.net/rexonms/hyMxq/

HTML

HTML

<div id="nav"> NAVIGATION
  <div class="message">div name</div>
</div>
<div id="main">
<div id="a">Div A</div>
<div id ="b"> Div B</div>
<div id ="c"> Div C</div>
</div>?

CSS

CSS

#nav {
    height: 50px;
    background-color: #999;
    position:fixed;
    top:0;
    width:100%;

}

#main{
    margin-top:55px;
}
#a, #b, #c {
    height:300px;
    background-color:#ddd;
    margin-bottom:2px;
}

SCRIPT

脚本

$(window).scroll(function() {

    var b = $('#b').position();

    $('.message').text(b.top);

    if (b.top == 55) {
        $('.message').text("Div B");
    }
});?

回答by j08691

Try this jsFiddle example

试试这个jsFiddle 例子

$(window).scroll(function() {
    var scrollTop = $(window).scrollTop(),
        divOffset = $('#b').offset().top,
        dist = (divOffset - scrollTop);
    $('.message').text(dist);
    if (b.top == 55) {
        $('.message').text("Div B");
    }
});?

Your original code was only checking the position of the div relative to the top of the document which never changes. You need to calculate in the amount of scroll the window has incurred and calculate accordingly.

您的原始代码仅检查 div 相对于文档顶部的位置,该位置永远不会改变。您需要计算窗口产生的滚动量并进行相应计算。

Also note the difference beyween jQuery's .position()and .offset()methods. The .position()method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document.

还要注意 jQuery.position().offset()方法之间的区别。该.position()方法允许我们检索元素相对于偏移父元素的当前位置。将此与 对比.offset(),后者检索相对于文档的当前位置。