Get position of each element

2019-09-19 13:21发布

问题:

$(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.

回答1:

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());
            }

        }