简体   繁体   中英

Get position of each element

 $(function(){ var $animatedEls = $(".marked"); $(window).scroll(function(e) { var offset = 0; $.each($animatedEls, function(i, item) { offset = $(item).offset().top; console.log($(item).offset()); }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> <div>...</div> <h2 class="marked">This sucks.</h2> 

I am trying to get the position of some matched elements when scrolling. The output is however the same number for each element.

Output:

Object {top: 2480, left: 0}
Object {top: 2480, left: 0}
Object {top: 2480, left: 0}

Why is the offset the same for each element? The values are also changing when I scroll.

EDIT: Okay. The snippet works on here, but not on my site. Highly annoying.

The problem is in the use of .each.

It should be used like this:

var $animatedEls = $('.marked');

        $(window).scroll(function(e) {

            $.each($animatedEls, function(index, item) {
                console.log($(item).offset());
            }

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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