获取每个元素的位置

时间:2015-05-17 19:21:30

标签: javascript jquery each offset

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

我想在滚动时获取一些匹配元素的位置。 但是,每个元素的输出数字相同。

输出:

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

为什么每个元素的偏移量相同? 滚动时,值也会发生变化。

编辑:好的。该代码段可在此处运行,但不在我的网站上。非常烦人。

1 个答案:

答案 0 :(得分:0)

问题在于使用.each。

它应该像这样使用:

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

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

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

        }