Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

javascript - how can I stick the div after scrolling down a little

I wanted to stick the 2nd div when we scroll down the page and when the 2nd div meets the top boundary. When it's fixed, it should scroll along with the other pages. How can I achieve this?

#settings{
    width:100%;
    background:#383838;
    height:60px;
}
#menu{
    width:100%;
    position:relative;
    height:100px;
    background:#aaa;
}
#body-content{
    height:900px;
    position:relative;
}

and the HTML

<body>
<div id="top">
    <div id="settings">
    </div>
    <div id="menu">
    </div>
</div>
<div id="body-content">
</div>

</body>

Here in this example http://jsfiddle.net/WBur3/ , the 2nd div should be fixed when we scroll the page. When we scroll up, should turn into the previous state itself. Please help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get this effect with jquery

$(function(){
        // Check the initial Poistion of the Sticky Header
        var stickyHeaderTop = $('#stickyheader').offset().top;

        $(window).scroll(function(){
                if( $(window).scrollTop() > stickyHeaderTop ) {
                        $('#stickyheader').css({position: 'fixed', top: '0px'});
                        $('#stickyalias').css('display', 'block');
                } else {
                        $('#stickyheader').css({position: 'static', top: '0px'});
                        $('#stickyalias').css('display', 'none');
                }
        });
  });

DEMO HERE

NOTE: Don't forget to include jquery library link in your page (assuming you as beginner)

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...