超过一定高度对象自动悬浮

<script type="text/javascript">
    var navH = document.getElementById('id').offsetTop;//获取要定位元素距离浏览器顶部的距离
    window.onscroll = function(){
        var scroH = document.documentElement.scrollTop || document.body.scrollTop;//获取滚动条的滑动距离
        var bar = document.getElementById('id');
        if(scroH>=navH){//滚动条的滑动距离大于等于定位元素距离浏览器顶部的距离,就固定,反之就不固定
            bar.style.position  = "fixed";
            bar.style.top  = "0px";
        }else if(scroH<navH){
            bar.style.position  = "static";
        }
    }
</script>

可以根据实际需要效果更改if和else里面的属性。

posted @ 2015-03-28 11:42  秋月白  阅读(175)  评论(0编辑  收藏  举报