阅读 195

来个横向电梯导航

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style type="text/css">
    *{
        margin: 0;
        padding: 0;
    }
    img{
        border:0;
    }
    ol, ul ,li{list-style: none;} 
        body > div div{
            width:800px;
            height:400px;
            margin: 40px auto;
            border:1px #ccc solid;
        }
        #one {background-color: red;}
        #two {background-color: blue;}
        #three {background-color: grey;}
        #four {background-color: skyblue;}
    .nav a {display:inline-block;margin:0 30px;padding: 0 20px;color:#fff;line-height: 50px;}
    .nav {width:100%;position: fixed;top:0;}
    .nav nav {margin: 0 auto;width:1200px;text-align: center;height:50px;background-color: black;}
    .nav .active {background-color: red;transition: all .2s;}
    #topel {margin-top: 100px;}

    .nav a:hover{background-color: red;}
    </style>
</head>
<body>
<div class="nav">
    <nav>
        <a href="#one" class="active">第一</a>
        <a href="#two">第二</a>
        <a href="#three">第三</a>
        <a href="#four">第四</a>
    </nav>
</div>
    <div id="topel">
        
        <div id="one"></div>
        <div id="two"></div>
        <div id="three"></div>
        <div id="four"></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
    </div>
    <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
    $(function () {
        $('.nav a').on('click',function () {
            $(this).addClass('active').siblings('a').removeClass('active');
        });

        $(window).scroll(function(event) {
            function offset (x,m,n,j,num1,num2) {
        function addes (y) {$(y).addClass('active').siblings('a').removeClass('active');}
                if ( x == 0) {addes('.nav a:eq(0)');}
            if (x >= m - num1 && x <= m + num2) {addes('.nav a:eq(1)'); }
             if (x >= n - num1 && x <= n + num2) {addes('.nav a:eq(2)'); }
             if (x >= j - num1 && x <= j + num2) {addes('.nav a:eq(3)'); } 
         }
            offset($(this).scrollTop(),two.offsetTop,three.offsetTop,four.offsetTop,90,40)
        });
        console.log($('#two').offset().top);//等价console.log(two.offsetTop);
        console.log($(window).scrollTop());
        console.log(document.documentElement.scrollTop)
    })
    </script>
</body>
</html>

复制代码