Get position of each element

扶醉桌前 提交于 2020-01-06 13:51:55

问题


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

        }


来源:https://stackoverflow.com/questions/30291125/get-position-of-each-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!