Rumah  >  Soal Jawab  >  teks badan

javascript - 如何固定一块div滑动到一定位置之后不再滑动?

如何固定一块p滑动到一定位置之后不再滑动?
例如:http://segmentfault.com/q/1010000000312781这个页面中的“转发分享”和“相关问题”,在滑动到页面顶部的时候不再滑动了。

怪我咯怪我咯2749 hari yang lalu558

membalas semua(5)saya akan balas

  • PHP中文网

    PHP中文网2017-04-10 13:12:57

    主要是通过onscroll判断位置和高度,并修改style。最终还是要用position:fixed。
    写了一个大概是最简单的用例,于是有些css细节没照顾到。你看看是否有帮助。

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style type="text/css">
    body{
        width:40em;
        margin:0 auto;
    }
    article{
        float:left;
    }
    aside{
        float:right;
    }
    p{
        line-height:3em;
    }
    </style>
    </head>
    <body>
    <article>
    <p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p><p>内容</p>
    </article>
    <aside>
    <p>侧边栏</p><p>侧边栏</p><p>侧边栏</p>
    <p id="float"><p>漂浮侧边栏</p></p>
    </aside>
    <script type="text/javascript">
    window.onload=
    function(){
        var op = document.getElementById("float"),
        H = 0,
        Y = op
        while (Y) {H += Y.offsetTop; Y = Y.offsetParent}
        window.onscroll = function()
        {
            var s = document.body.scrollTop || document.documentElement.scrollTop
            if(s>H) {
                op.style = "position:fixed;top:0;"
            } else {
                op.style = ""
            }
        }
    }
    </script>
    </body>
    </html>
    

    balas
    0
  • 迷茫

    迷茫2017-04-10 13:12:57

    试试设置 position:fixed 试试

    balas
    0
  • 天蓬老师

    天蓬老师2017-04-10 13:12:57

    用js实现监听。设定滚动到某个位置的时候,修改该p的style, position:fixed

    balas
    0
  • ringa_lee

    ringa_lee2017-04-10 13:12:57

    我用的是sticky插件的,但是插件原来的显示方式会溢出。
    怎么办呢?我研究了下源码,在他计算底部距离的时候,我加了个

    var $parentElement = s.stickyElement.parents(s.containerSelector);
    var bos = documentHeight-($parentElement.offset()?$parentElement.offset().top:0)-($parentElement.height()?$parentElement.height():0);
    s.bottomSpacing=s.defaultBottom+bos;
    

    就是插件要额外计算底部留空,我在这个基础上在多加了他父级元素的高和顶部距离,保证他不会溢出他的父辈。

    虽然感觉有点亡羊补牢,之后会再改改吧。

    balas
    0
  • 高洛峰

    高洛峰2017-04-10 13:12:57

    有个position:sticky,这个属性比较新

    balas
    0
  • Batalbalas