简体   繁体   中英

Scrolling/fixed sidebar gets cut off when sidebar is very long

I have a small jQuery script to keep the sidebar visible when you scroll down the browser. However, the sidebar can get very long since it will contain filters (dropdowns and checkboxes) so the bottom part gets cut-off.

I'd like to have an effect like on this website:

http://www.lyst.com/

In a way, when the sidebar is long, you are still able to scroll up and down. It will only become fixed when it reaches the bottom/top of the sidebar.

Does anybody know where I can get a script that does this exactly?

Set your CSS and HTML markup in a fashion that you can easy reference the objects you want to avoid collision with. Create conditional statements to compare said references.

Firstly, the working jsFiddle.

The HTML ->

<div class="content">
    <div class="main">
        Main Content
    </div>
    <div class="sidebar">
        Sidebar
    </div>
    <div class="footer">
        Footer
    </div>
</div>

The CSS ->

#content{
  position:relative; /* required */
  height:2000px;    
}
.main{
  margin-left:100px;
  border:1px solid rgb(120,120,120);
  height:1500px;  
}
.sidebar{
  position:absolute; /* required */
    top:25px; /* required -- does NOT need to be this value, however. */
    left:5px; /* required -- does NOT need to be this value, however.*/
  border:1px solid rgb(8,8,8);
  background:rgba(70,70,70,.9);  
  color:#ecebeb;
  width:93px;    
}
.footer{
  border-top:1px solid #ff0000;
  height:498px;    
}

The jQuery ->

$(window).scroll(function(){
    var dist = $(window).scrollTop();
    var sTop = $('.sidebar').position().top;
    var mHeight = $('.main').height();
    var userDist = 100;
    if((sTop > (mHeight - userDist)) && (dist > (mHeight - userDist))){
        //the sidebar is pinned now. it won't scroll further.
    }else if(dist < (mHeight - userDist)){
        $('.sidebar').animate({
            top: dist + $('.sidebar').height()
        }, 0);         
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM