美文网首页
滚动监听

滚动监听

作者: 阿鲁提尔 | 来源:发表于2018-08-14 11:38 被阅读0次

原型图

在线地址

http://js.jirengu.com/neliz

代码

HTML:
<div class="pageContentScan_box">
    <span>菜单1</span>
    <span>菜单2</span>
    <span>菜单3</span>
</div>

<section class="needScanPosition">内容1</section>
<section class="needScanPosition">内容2</section>
<section class="needScanPosition">内容3</section>

// needScanPosition 就是跳转的项目

JS:
(function ($) {
    var tab_t = {
        width: $('.pageContentScan_box').get(0).offsetWidth,
        height: $('.pageContentScan_box').get(0).offsetHeight,
        topDistance: $('.pageContentScan_box').get(0).offsetTop
    };
    var tab_c_topDistanceArray = [];
    $('.needScanPosition').each(function (e) {
        var distance = $('.needScanPosition').eq(e).get(0).offsetTop;
        tab_c_topDistanceArray.push(distance);
    });
    function judgeScroll() {
        var winScroll = $(window).scrollTop();
        if (winScroll > tab_t.topDistance) {
            $('.pageContentScan_box').addClass('fixTop');
            for (var i = 0; i < tab_c_topDistanceArray.length; i++) {
                if (winScroll >= (tab_c_topDistanceArray[i] - tab_t.height)) {
                    $('.pageContentScan_box span').removeClass('current').eq(i).addClass('current');
                    console.log(i);
                }
            }
        } else {
            $('.pageContentScan_box span').removeClass('current')
            // .eq(0).addClass('current');
            $('.pageContentScan_box').removeClass('fixTop');
        }
    }
    judgeScroll();
    $(window).scroll(function () {
        judgeScroll();
    });
    $('.pageContentScan_box span').click(function (e) {
        var ele = e.target;
        var eleIndex = $(ele).index();
        $(window).scrollTop(tab_c_topDistanceArray[eleIndex] - tab_t.height);
    });
})(jQuery);

相关文章

网友评论

      本文标题:滚动监听

      本文链接:https://www.haomeiwen.com/subject/uelubftx.html