Swap CSS class on the basis of Scroll Position with Javascript

前端 未结 2 1893
天涯浪人
天涯浪人 2020-12-15 14:36

I\'m looking to re-create the Apple Store shopping cart sidebar.

http://store.apple.com/us/configure/MB535LL/A?mco=MTA4MTg3NTQ

It is similar to \"position:

相关标签:
2条回答
  • 2020-12-15 15:14

    This working in FF3.5!

    <div id="banner" style="border:1px solid blue;width:100%;height:100px;">
     This is a banner1
    </div>
    <div style="clear:left;border:1px solid green;width:70%;height:900px;top:110;">
        this is main div
    </div>
    <div id="fixedDiv" 
                 style="clear:left;position:absolute;top:110;right:20;width:25%;
                 border:1px solid red;height:500px;">
        lorem ipsum dorem dorel ipsa zeta zelga rumba lorem ipsum dorem dorel ipsa 
        zeta zelga rumba lorem ipsum dorem dorel ipsa zeta zelga rumba
    </div>
    
    <script type="text/javascript">
        var abs=false; //dont set it again and again
     $(document).ready(function(){
         $().scroll(function(e){
      var st=$(window).scrollTop();
      //110 is top of fixedDiv
      if(st>110)
      {
                    //set number to how much you want it from top!
                    $("#fixedDiv").css({"top":10}); 
                    if(abs) return;
                    $("#fixedDiv").css({"position":"fixed"});
                    abs=true;
                }
                else
                {
                    if(!abs) return;
                    //if we are again showing banner, change position to absolute
                    $("#fixedDiv").css({"position":"absolute","top":110}); 
                    abs=false;
                }
           });
       });
    </script>
    
    0 讨论(0)
  • 2020-12-15 15:38

    You will have to handle the window.onscroll event, and check the element position, if the scrollTop is greater than the position of your element, you set the element fixed at top, if not, you place the element where it originally was.

    An example using jQuery:

    $(function () { 
      var $el = $('.fixedElement'), 
          originalTop = $el.offset().top;  // store original top position
    
      $(window).scroll(function(e){ 
        if ($(this).scrollTop() > originalTop ){ 
          $el.css({'position': 'fixed', 'top': '0px'}); 
        } else { 
          $el.css({'position': 'absolute', 'top': originalTop}); 
        } 
      }); 
    });
    
    0 讨论(0)
提交回复
热议问题