Fixed navigation bar demo

code show as below

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{margin:0;padding:0}
        img{
            vertical-align: top;
        }
        .main{
            margin:0 auto;
            width:1000px;
            margin-top:10px;

        }
        .fixed {
            position: fixed;
            top: 0;
            left: 0;
        }
    </style>
</head>
<body>
<div class="top" id="top">
    <img src="images/top.png" alt=""/>
</div>
<div class="nav" id="Q-nav">
    <img src="images/nav.png" alt=""/>
</div>
<div class="main">
    <img src="images/main.png" alt=""/>
</div>
</body>
</html>
<script src="my.js" type="text/javascript"></script>
<script>
   var nav = $("Q-nav" );
    var navTop = nav.offsetTop;   // Get the distance from the top of the navigation bar 168 
   console.log(navTop);
    window.onscroll = function() {
       // console.log(nav.offsetTop);
        if(scroll().top >= navTop)
        {
            // alert("to the position"); 
            nav.className = "nav fixed" ;
        }
        else
        {
            nav.className = "nav";
        }
    }
</script>

my.js is a small plug-in packaged for itself

function scroll() {
     if (window.pageYOffset != null )   //   ie9+ and other browsers 
    {
         return {
            left: window.pageXOffset,
            top: window.pageYOffset
        }
    }
    else  if (document.compatMode == "CSS1Compat")   // declared DTD 
    // check if it's a browser in weird mode -- just not declared <!DOCTYPE html> 
    {
         return {
            left: document.documentElement.scrollLeft,
            top: document.documentElement.scrollTop
        }
    }
    return { //   The rest must be the left of the weird mode 
        : document.body.scrollLeft,
        top: document.body.scrollTop
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325292970&siteId=291194637