JS如何实现导航栏的智能浮动

<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() 这是获取水平滚动条的距离

posted @ 2016-04-30 23:04  张林-布莱恩特  阅读(898)  评论(0编辑  收藏  举报
博客统计by flagcounter: