简体   繁体   English

如何在滚动时获得div顶部位置值

[英]How to get the div top position value while scrolling

I am trying to run some script when div reaches to a certain point when it's scrolled. 当div滚动到达某个点时,我正在尝试运行一些脚本。 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. 我正在使用$(window).scroll函数,但它只检查div位置一次而不是更新值。 How to make scroll check the window size every 5-10 px move so that it doesn't take too much memory/processing. 如何滚动检查窗口大小每5-10 px移动,以便它不需要太多的内存/处理。 The code is set up at: http://jsfiddle.net/rexonms/hyMxq/ 代码设置在: 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");
    }
});​

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. 您的原始代码仅检查div相对于文档顶部的位置,该位置永远不会更改。 You need to calculate in the amount of scroll the window has incurred and calculate accordingly. 您需要计算窗口已经发生的滚动量并相应地进行计算。

Also note the difference beyween jQuery's .position() and .offset() methods. 还要注意jQuery的.position().offset()方法之间的.offset() The .position() method allows us to retrieve the current position of an element relative to the offset parent. .position()方法允许我们检索元素相对于偏移父元素的当前位置。 Contrast this with .offset() , which retrieves the current position relative to the document. 将此与.offset()对比,后者检索相对于文档的当前位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM