jquery实现滚动监听实例

css:

  <style>
        * {
            list-style: none;
        }

        div {
            width: 100%;
            height: 1000px;
            background: skyblue;
        }

        div:nth-child(2) {
            background: lightpink;
        }

        div:nth-child(3) {
            background: lightgreen;
        }

        div:nth-child(4) {
            background: lightcoral;
        }

        ul {
            position: fixed;
            right: 30px;
            width: 100px;
            height: 100px;
            margin: auto;
            top: 0;
            bottom: 0;
            border: 1px solid blue;
            padding: 0;
        }

        li {
            width: 100%;
            height: 25%;
            line-height: 25px;
            border-bottom: 1px solid blue;
            box-sizing: border-box;
            text-align: center;
        }

        li.active {
            color: red;
        }
    </style>

html:

 <div></div>
    <div></div>
    <div></div>
    <div></div>
    <ul>
        <li class="active">新闻1</li>
        <li>新闻2</li>
        <li>新闻3</li>
        <li>新闻4</li>
    </ul>

javascript:

//jquery官网:https://www.bootcdn.cn/jquery/  
<script src="./js/jquery.js"></script>
    <script>
        /* 
            页面滚动的时候 判断页面的滚动距离 与元素的距离页面的距离做判断
        */
        $(window).scroll(function () {
            
            $('div').each(function (i, v) {
                if ($(window).scrollTop() >= $('div').eq(i).offset().top) {
                    $('li').eq(i).addClass('active').siblings().removeClass('active');
                }
            });
        });

        /* 
            点击li  让页面跳转到对应的div的位置
        */
        $('li').click(function () {
            $(this).addClass('active').siblings().removeClass('active');
            // 让页面跳转到对应的位置
            // 对应的下标
            var i = $(this).index();
            // console.log(i, $('div').eq(i).offset().top);
            $('html,body').animate({'scrollTop': $('div').eq(i).offset().top});
        });
    </script>

效果:

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值