JS如何實現導航欄的智慧浮動

操張林發表於2016-04-30

<script language=”javascript”>
    function smartFloat(obj) {
        var obj = document.getElementById(obj);
        var top = getTop(obj);
        var isIE6 = /msie 6/i.test(navigator.userAgent);
        window.onscroll = function () {
            var bodyScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            if (bodyScrollTop > top) {
                obj.style.position = (isIE6) ? “absolute” : “fixed”;
                obj.style.top = (isIE6) ? bodyScrollTop + “px” : “0px”;
            } else {
                obj.style.position = “static”;
            }
        }
        function getTop(e) {
            var offset = e.offsetTop;
            if (e.offsetParent != null) offset += getTop(e.offsetParent);
            return offset;
        }
    }
    window.onload = function () {
        smartFloat(“nav”);
    }

   </script>

****擴充套件*****

 //原生JS
    //獲取div距離頂部的距離
    var mTop = document.getElementsByClassName(`mdiv`)[0].offsetTop;
     //獲取滾動條的高度
    var sTop = document.body.scrollTop;
  //Jquery
    mTop = $(`.mdiv`)[0].offsetTop;
    sTop = $(window).scrollTop();

$(document).scrollTop() 獲取垂直滾動的距離  即當前滾動的地方的視窗頂端到整個頁面頂端的距離
$(document).scrollLeft() 這是獲取水平滾動條的距離


相關文章