如何使用each()方法缩短代码?

时间:2018-12-18 12:46:27

标签: javascript jquery foreach

我有一个问题。我有一个脚本:

$(document).ready(function () {
    $(document).on('scroll', function () {

        const windowHeight = $(window).height()
        const scrollValue = $(this).scrollTop();

        const $art1 = $('.art1');
        const art1FromTop = $art1.offset().top
        const art1Height = $art1.outerHeight()

        const $art2 = $('.art2');
        const art2FromTop = $art2.offset().top
        const art2Height = $art2.outerHeight()

        const $art3 = $('.art3');
        const art3FromTop = $art3.offset().top
        const art3Height = $art3.outerHeight()

        const $art4 = $('.art4');
        const art4FromTop = $art4.offset().top
        const art4Height = $art4.outerHeight()

        const $art5 = $('.art5');
        const art5FromTop = $art5.offset().top
        const art5Height = $art5.outerHeight()

        const $art6 = $('.art6');
        const art6FromTop = $art6.offset().top
        const art6Height = $art6.outerHeight()

        const $art7 = $('.art7');
        const art7FromTop = $art7.offset().top
        const art7Height = $art7.outerHeight()

        if (scrollValue > art1FromTop + art1Height / 2 - windowHeight) {
            $art1.addClass('active');
        }

        if (scrollValue > art2FromTop + art2Height / 2 - windowHeight) {
            $art2.addClass('active');
        }

        if (scrollValue > art3FromTop + art3Height / 2 - windowHeight) {
            $art3.addClass('active');
        }

        if (scrollValue > art4FromTop + art4Height / 2 - windowHeight) {
            $art4.addClass('active');
        }

        if (scrollValue > art5FromTop + art5Height / 2 - windowHeight) {
            $art5.addClass('active');
        }

        if (scrollValue > art6FromTop + art6Height / 2 - windowHeight) {
            $art6.addClass('active');
        }

        if (scrollValue > art7FromTop + art7Height / 2 - windowHeight) {
            $art7.addClass('active');
        }
    })
})

我想使用each()将其更改为较短的一个。我要记住,例如,我必须使用$('。art')来选择该类中的所有div,然后将它们从1开始迭代的数字相加。但是,如何计算每个div的滚动位置?我该如何确定每个div的位置?我必须按现在的方式选择它,还是可以使用“ this”?

1 个答案:

答案 0 :(得分:0)

在执行相同操作时,请使用Multiple Selector,然后使用.filter()根据用于测试集合中每个元素的函数来获取匹配的元素。 this是当前的DOM元素。

$(document).on('scroll', function () {

    const windowHeight = $(window).height()
    const scrollValue = $(this).scrollTop();

    var arts = $('.art1, .art2, ..., .art7'); //better $('.art')

    arts.filter(function(){
        const $art = $(this);
        const artFromTop = $art.offset().top
        const artHeight = $art.outerHeight()

        return scrollValue > artFromTop + artHeight / 2 - windowHeight;            
    }).addClass('active');
});