jquery div固定在顶部(div顶部吸附)

发布时间:2015-08-10 10:00 | 人气数:1721

一、JS div顶部吸附代码参考:

<!DOCTYPE html>
<html><head>
<style type="text/css">
    .wrapper{width:1000px;height:2000px;margin-left:auto;margin-right:auto}
    .header{height:150px;}
    #nav{padding:10px;position:relative;top:0;background:black;width:1000px}
    a{display:inline-block;margin:0 10px;*display:inline;zoom:1;color:white}
</style>
</head>
<body>
    <div class="wrapper">
        <div class="header"></div>
        <div id="nav">
            <a href="#">栏目导航</a>
            <a href="#">栏目导航</a>
            <a href="#">栏目导航</a>
            <a href="#">栏目导航</a>
            <a href="#">栏目导航</a>
        </div>
    </div>
</body>
</html>
<script type="text/javascript">
function menuFixed(id){
    var obj = document.getElementById(id);
    var _getHeight = obj.offsetTop;
    
    window.onscroll = function(){
        changePos(id,_getHeight);
    }
}
function changePos(id,height){
    var obj = document.getElementById(id);
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    if(scrollTop < height){
        obj.style.position = 'relative';
    }else{
        obj.style.position = 'fixed';
        /*给元素添加`fixed`固定属性
        也可以添加写好的CSS样式`obj.className = 'fix_css';`*/
    }
}
window.onload = function(){
    menuFixed('nav');
}
</script>
二、引用JS框架Bootstrap,直接使用附加导航(Affix) bootstrap-affix.js,只需添加data-spy="affix"到任意需要监听的页面元素上,就可以很容易的将其变为附加导航。然后使用偏移量来控制其位置。
<div data-spy="affix" data-offset-top="200">...</div>
通过JavaScript启动:$('#navbar').affix()
关键词:JavaScript, bootstrap, jquery, css, 特效