更改符合列表中某些条件的对象

时间:2014-09-26 17:13:35

标签: jquery

我希望在列表项位于屏幕上的特定位置之上时更改列表项的css(特别是颜色)。当第一个列表项位于位置上方时,我可以更改整个列表,但我似乎无法弄清楚如何只更改标记之上的项目。

示例,首先看小提琴:http://jsfiddle.net/wzfu322h/

for (i = 1; i <= 100; i++) {
    $('#list').append('<li id="li' + i + '">' + i + '</li>');
}
var containerBottom = document.getElementById("container").getBoundingClientRect().bottom - 25;

var listElement = $('li');
var checkScroll = function () {
    if ($('#container').find(listElement).position().top < containerBottom) {
        $('#container').find(listElement).css("color", "#FFF");
    }
};
$('#container').scroll(checkScroll);

我尝试使用find()以及其他方法,例如:sibling()children(),但不确定这是否是正确的方法。我知道我正在通过更改$('#container')对象来更改所有列表项的css。直接的问题是,如何在列表中传递特定物理位置时更改每个列表项? (在这种情况下,在其容器底部上方25px处)

1 个答案:

答案 0 :(得分:0)

您需要分别在每个列表项上运行您的函数:

var listElement = $('#container li');

var checkScroll = function () {
    $(listElement).each(function () {
        if ($(this).position().top < containerBottom) {
            $(this).css("color", "#FFF");
        }
    });
};

Demo

相关问题