div顶部吸附

功能:

滚动页面时div到达顶部时固定在顶部

原生实现:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #title{
            background: #ddd;
            width: 100%;
            padding:30px;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
<div class="a" style="height:200px;"></div>
<div id="title">hello world</div>
<div class="d" style="height: 1000px;"></div>
<script>
    var a;
    var title = document.getElementById('title');
    var v = title.offsetTop;//存储原来的距离顶部的距离
    window.onscroll = function(){
        a = document.documentElement.scrollTop;//存储滚动高度
        if(a>v){
            title.style.position = 'fixed';
            title.style.top = 0;
        }else if(title.style.position != 'static'){
            title.style.position = 'static';
        }
    }
</script>
</body>
</html>

jquery实现:

<!DOCTYPE html>
<html>

<head>
    <title></title>
    <style type="text/css">
    #text {
        background: #ffffff;
        width: 100%;
        padding:30px;
    }
    </style>
</head>

<body style="margin:0px;">
    <div style="height:300px;background:lightcoral"></div>
    <div id="text">div顶部吸附</div>
    <div style="height:2000px;background:lightblue"></div>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        var ie6 = document.all;
        var dv = $('#text');
        var st;
        dv.attr('otop', dv.offset().top); //存储原来的距离顶部的距离
        $(window).scroll(function() {
            st = Math.max(document.body.scrollTop || document.documentElement.scrollTop);
            if (st > parseInt(dv.attr('otop'))) {
                if (ie6) { //IE6不支持fixed属性,所以只能靠设置position为absolute和top实现此效果
                    dv.css({ position: 'absolute', top: st });
                } else if (dv.css('position') != 'fixed'){
                    dv.css({ 'position': 'fixed', top: 0 });
                } 
            } else if (dv.css('position') != 'static') {
                dv.css({ 'position': 'static' });
            }
        });
    });
    </script>
</body>

</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,693评论 1 92
  • 请参看我github中的wiki,不定期更新。https://github.com/ivonzhang/Front...
    zhangivon阅读 12,189评论 2 19
  • 在线阅读 http://interview.poetries.top[http://interview.poetr...
    前端进阶之旅阅读 115,307评论 24 450
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,665评论 4 61
  • 在平时上台说话或者演讲时,一些人总是说自己没有自信,我也是这样的,但是后来听到了一些技巧,觉得还有几分道理,我说给...
    本喜尔玉阅读 4,007评论 0 0

友情链接更多精彩内容