模仿淘宝、京东的滚动条事件

当页面的某个模块的顶端与浏览器的顶端相遇时,滚动条相应的小方格就会改变样式,提示用户当前浏览到了哪一个模块。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.12.3.min.js"></script>
    <style>
        #nav div{height: 100px;line-height: 100px;text-align: center}
        .active{
            background: green;
            border-radius: 100%;
            font-size: 35px;
            color: white;
            box-shadow: 5px 5px 5px black;
        }
    </style>
</head>
<body>
<script>
    //$(window).scrollTop()是滚到上面的高度
    //$(window).height()屏幕的高度
$(function(){
    var arry=["news","shipin","jianjie","nihao"];

    $(window).scroll(function(event){
        console.log(event)
       var scrollTop= $(window).scrollTop();
        if(scrollTop>200){
            $("#returnT").show()
        }else{
            $("#returnT").hide()
        }
        for(var i=0;i<arry.length;i++){
            if(scrollTop>=$('#'+arry[i]).offset().top && ($('#'+arry[i]).offset().top+$('#'+arry[i]).height())>scrollTop){
                $('#nav div:eq('+i+')').addClass('active')
            }else{
                $('#nav div:eq('+i+')').removeClass('active')
            }
        }
    });

    $("#nav div").each(function(){
        $(this).click(function(){
            $("html,body").animate({scrollTop:$("#"+arry[$(this).index()]).offset().top},500)
        })
    })

    $("#returnT").click(function(){
        $("html,body").animate({scrollTop:0},500)
    })
})

</script>
<div id="nav" style="position: fixed;top:30px;right:0;width:100px;border: 1px solid black;background: yellow;">
    <div>新闻</div>
    <div>视频</div>
    <div>简介</div>
    <div>你好</div>
</div>
<div id="news" style="height:800px;background: red">新闻</div>
<div id="shipin" style="height:800px;background: yellow">视频</div>
<div id="jianjie" style="height:800px;background: green">简介</div>
<div id="nihao" style="height:800px;background: red">你好</div>
<div id="returnT" hidden style="position: fixed;bottom: 0;right: 0;width: 100px;height: 100px;background: gray">回到顶部</div>
</body>
</html>

  

posted @ 2017-02-08 16:37  刘浩2561179983  阅读(248)  评论(0编辑  收藏  举报